import React, { Component } from 'react';
import './scss/LineChat.scss';
import { getData, getData1, getRealPath, getQueryVariable, putData1, delData, postData, putData } from '../../common/js/fetch';
import { message, Tooltip } from 'antd';
import {
    LgButton, LgSelect, LgBlockCard, lgAlert, LgDatePicker, LgSearch, LgPaginationC, LgUpload,
    LgBlockCardBoxProps, LgPopLayer, LgDrawer, LgInput, LgCheckbox, LgTextarea, LgSwitch, LgEmpty, LgLoadingDotRotation
} from 'lancoo-web-ui';
import 'element-theme-default';
import { Scrollbars } from 'react-custom-scrollbars';
import MyEditor from './MyEditor'
// import MyEditor from './EditorV4'
import dayjs from 'dayjs'
import { w3cwebsocket as W3CWebSocket } from 'websocket';
import Zmage from 'react-zmage';
import Viewer from 'viewerjs';
import 'viewerjs/dist/viewer.min.css';

class LineChat extends Component {
    scrollbarsRef = React.createRef();
    constructor(props) {
        super(props);
        this.state = {
            openSettingVisible: false,
            openChatHistory: false,
            chatContent: '',
            isIframe: sessionStorage.getItem('isIframe'),
            blockPerson: false,
            disturbing: false,
            onlyViewPerson: false,
            historyDate: dayjs().format('YYYY-MM-DD'),
            demonstrationValue: new Date(),
            token: getQueryVariable('lg_tk') || sessionStorage.getItem('token'),
            isClear: false,
            menuVisible: false,
            menuIndex: null,
            session: null,
            sessionId: null,
            sessionList: [],
            userInfo: JSON.parse(sessionStorage.getItem('userInfo')),
            schoolInfo: JSON.parse(sessionStorage.getItem('schoolSystemInfo')),
            pageNum: 1,
            pageSize: 10,
            pageHistoryNum: 1,
            pageHistorySize: 8,
            chatHistory: [],
            receiverId: sessionStorage.getItem('receiverId'),
            receiverName: decodeURIComponent(sessionStorage.getItem('receiverName')),
            receiverAvatarPath: decodeURIComponent(sessionStorage.getItem('receiverAvatarPath')),
            groupId: sessionStorage.getItem('groupId'),
            groupName: decodeURIComponent(sessionStorage.getItem('groupName')),
            isGroup: sessionStorage.getItem('isGroup'),
            openUserInfo: null,
            openOtherUserInfo: null,
            openUserVisible: false,
            showTime: false,
            showWithdraw: false,
            isShowWithdraw: false,
            showIndex: 0,
            showTimeIndex: 0,
            isSend: false,
            isReEdit: false,
            firstNum: 0,
            isSearch: false,
            selectedFile: null,
            keyword: '',
            notReceiver: false,
            isTop: false,
            isFetching: false,
            historyMessageList: [],
            isBlocking: false,
            isReminding: false,
            isChoosed: false,
            isBtnDel: false,
            totalNum: 0,
            userObj: null,
            isSeat: false,
            isDownload: false,
            downloadPercent: 0,
            clear: false,
            isFull: false,
            groupUserList: [],
            searchGroupList: [],
            groupUserItem: null,
            groupUserKeyword: '',
            userSearch: false,
            screenWidth: '1825',
            openBanned: false,
            isBannedList: [],
            allBanned: false,
            speakMemberList: [],
            noBannedAll: false,
            groupInfo: {},
            timeList: [
                {
                    text: "5分钟",
                    key: '1'
                },
                {
                    text: "1小时",
                    key: '2'
                },
                {
                    text: "1天",
                    key: '3'
                },
                {
                    text: "7天",
                    key: '4'
                },
                {
                    text: "30天",
                    key: '5'
                },
            ],
            openBannedPerson: false,
            cancelBannedPerson: false,
            bannedKeyword: '',
            noBannedKeyword: '',
            bannedSearch: false,
            noBannedSearch: false,
            searchBannedList: [],
            bannedList: [],
            bannedSelectList: [],
            bannedCloseList: [],
            bannedSelectCloseList: [],
            noBannedList: [],
            bannedAll: false,
            selectValue: '5分钟',
            searchNoBannedList: [],
        }
    }
    //发布消息自动滚动到底部
    scrollToBottom() {
        if (this.scrollbarsRef.current) {
            setTimeout(() => {
                this.scrollbarsRef.current.scrollToBottom();
            }, 150);
        }
    }

    // 防抖函数
    debounce = (func, delay) => {
        let timer;
        console.log('func', func);

        return function () {
            clearTimeout(timer);

            timer = setTimeout(() => {
                func.apply(this, arguments);
            }, delay);
        };
    }
    // 挂载后
    componentDidMount() {
        console.log(window.screen.availWidth)
        console.log(document.body.clientWidth)
        //登录
        this.connectWebSocket();
        this.setState({
            loading: true
        })

        // 添加点击事件监听
        let $this = this;
        document.addEventListener('click', function (event) {
            // 判断点击的元素是否为要下载的链接
            if (event.target.classList.contains('file-down')) {
                event.preventDefault(); // 阻止默认的下载行为

                var downloadLink = event.target.getAttribute('href'); // 获取下载链接
                var customFilename = event.target.getAttribute('download'); // 获取自定义的文件名

                var xhr = new XMLHttpRequest();
                xhr.open('GET', downloadLink);
                xhr.responseType = 'blob';
                $this.setState({
                    isDownload: true,
                })

                // 监听下载进度
                xhr.addEventListener('progress', function (event) {
                    if (event.lengthComputable) {
                        var percentComplete = (event.loaded / event.total) * 100;
                        console.log('下载进度：' + percentComplete.toFixed(2) + '%');
                        $this.setState({
                            downloadPercent: percentComplete.toFixed(2),
                        })
                    }
                });

                xhr.onload = function () {
                    if (xhr.status === 200) {
                        var blob = xhr.response;

                        // 创建下载链接
                        var url = window.URL.createObjectURL(blob);

                        // 创建隐藏的 <a> 标签
                        var link = document.createElement('a');
                        link.href = url;
                        link.download = customFilename;
                        link.target = '_blank';

                        // 模拟点击隐藏的 <a> 标签来触发文件下载
                        link.click();

                        // 释放创建的 URL 对象
                        window.URL.revokeObjectURL(url);
                        setTimeout(() => {
                            $this.setState({
                                isDownload: false,
                                downloadPercent: 0,
                            }, () => {
                                message.success('下载成功')
                            })
                        }, 300);
                    } else {
                        $this.setState({
                            isDownload: false,
                            downloadPercent: 0,
                        }, () => {
                            message.error('下载文件时发生错误')
                        })
                        console.error('下载文件时发生错误：', xhr.status);
                    }
                };

                xhr.send();
            }
        });


    }

    componentWillUnmount() {
        this.closeWebSocket();
    }
    //登录
    connectWebSocket = () => {
        let {
            userInfo,
            chatHistory,
            schoolInfo,
        } = this.state
        // let client = new W3CWebSocket('ws://192.168.129.155:10376/im_chat/'); // 替换为实际的WebSocket地址
        // let client = new W3CWebSocket('ws://192.168.129.115:10376/chat'); // 替换为实际的WebSocket地址
        let client = new W3CWebSocket(schoolInfo.chatWs); // 替换为实际的WebSocket地址
        console.log(schoolInfo.chatWs, 'chatHistory', chatHistory);

        client.onopen = () => {
            console.log('WebSocket 连接已打开', userInfo);

            // 发送登录消息
            let loginData = {
                msgType: 3,
                clientType: '1',
                token: this.state.token, // 替换为实际的令牌
                data: {
                    userId: userInfo.userId // 替换为实际的用户ID
                }
            };
            console.log('loginData', loginData);
            client.send(JSON.stringify(loginData));
            // 监听 WebSocket 的 onmessage 事件
        };
        client.onmessage = (event) => {
            let data = JSON.parse(event.data);
            console.log('client接收数据', data);
            // 在收到服务器响应后调用获取会话列表
            if (data.code == '200') {
                if (data?.msgType == 3) { //登录
                    // this.createSession();
                    this.pullOfflineMessage();
                    // this.getSessionList();
                } else if (data?.msgType == 10) { //获取离线消息后拉取会话列表
                    // this.getSessionList();
                    this.createSession();
                } else if (data?.msgType == 4) {//会话列表
                    console.log('data', data);
                    let res = data.data
                    // 按照 seat 值进行排序，seat 值为 1 的排在前面
                    res.sort((a, b) => {
                        if (a.seat === 1 && b.seat !== 1) {
                            return -1;
                        } else if (a.seat !== 1 && b.seat === 1) {
                            return 1;
                        } else {
                            return 0;
                        }
                    });
                    this.setState({
                        sessionList: res
                    }, () => {
                        res = res.concat([]);
                        let result = res.find(item => ((item.receiverId && item?.receiverId == this.state.receiverId) || (item?.groupId && item?.groupId == this.state.groupId)));
                        let newSession = res.find(item => ((item.receiverId && item.receiverId == this.state.session?.receiverId) || (item.groupId && item.groupId == this.state.session?.groupId)))
                        console.log(this.state.firstNum, 'result', result, 'newSession11', newSession, 'this.state.session?.receiverId ', this.state.session?.receiverId, 'res', res);
                        if (result) {
                            if (!this.state.isChoosed) {
                                this.chooseChatObj(result);
                            } else {
                                if (newSession) {
                                    this.setState({
                                        session: newSession
                                    })
                                } else {
                                    this.chooseChatObj(result);
                                }
                            }
                        } else {
                            if (this.state.isSearch || newSession) return;
                            this.chooseChatObj(res[0]);
                        }
                    })
                } else if (data?.msgType == 8) {//最近消息列表
                    if (this.state.openChatHistory) {//历史记录（记录框）
                        this.setState({
                            historyMessageList: data.data.reverse(),
                            isFetching: false,
                            totalNum: data.total,
                        }, () => {
                            if (this.state.isBtnDel) {
                                this.setState({
                                    chatHistory: [],
                                    isBtnDel: false,
                                })
                            }
                        })
                    } else {//最近消息（聊天框）
                        let messageArr = this.state.chatHistory.concat([]);
                        // 获取完毕后设置 isFetching 为 false
                        this.setState({ isFetching: false });
                        if (Array.isArray(data.data)) {
                            if (data.data.length == 0) {
                                this.setState({
                                    isTop: true,
                                })
                            }
                            if (this.state.pageNum === 1) {
                                messageArr = data.data.reverse();
                            } else {
                                // 获取之前的消息记录
                                let oldSendMsg = data.data.reverse();
                                let msgId = messageArr[0].msgId;
                                let oldMsgId = oldSendMsg.findIndex(item => item.msgId === msgId);
                                if (oldMsgId > -1) {
                                    oldSendMsg.splice(oldMsgId);
                                }
                                messageArr = oldSendMsg.concat(messageArr);
                                // console.log('messageArr', messageArr);
                            }
                        }
                        messageArr.forEach(item => {
                            item.sending = 2;
                        })
                        for (let i = 0; i < messageArr.length; i++) {
                            messageArr[i].isOldSend = 0;
                            if ((i + 1) % 20 === 0) {
                                messageArr[i].isOldSend = 1;
                            }
                        }
                        if (messageArr.length > 0 && messageArr.length < 20) {
                            messageArr[0].isOldSend = 1;
                        }
                        this.setState({
                            chatHistory: messageArr
                        }, () => {
                            if (this.state.pageNum === 1) {
                                this.scrollToBottom();
                            } else {
                                let scrollbarElement = this.scrollbarsRef.current;
                                // scrollbarElement.scrollTop += data.data.length * 200;
                                console.log('scrollbarElement', scrollbarElement);

                            }
                        })
                    }
                } else if (data?.msgType == 1) { //单聊
                    if (data.data?.content && data.data?.receiverId == userInfo.userId && this.state.session?.receiverId == data.data?.senderId) {//接收端接收消息
                        let chatHistoryReceive = this.state.chatHistory.concat([]);
                        chatHistoryReceive.push(data.data);
                        console.log(this.state.session?.receiverId, '接收消息', '_____', this.state.session.groupId == data.data?.groupId);
                        // this.setState({
                        //     chatHistory: chatHistoryReceive
                        // }, () => {
                        //     this.scrollToBottom();
                        //     this.isReceiveSession(data.data);
                        //     setTimeout(() => {
                        //         this.getSessionList();
                        //     }, 100);
                        // })
                        const executeMethods = async () => {
                            await this.scrollToBottom();
                            if (userInfo.userId != data.data.senderId) {
                                await this.isReceiveSession(data.data);
                            }
                            if (this.state.session?.receiverId == data.data?.senderId) {
                                await this.setIsRead(this.state.session);
                            } else {
                                await this.getSessionList();
                            }
                            await new Promise((resolve) => setTimeout(resolve, 100)); // 模拟延迟操作
                        };

                        executeMethods().then(() => {
                            this.setState({
                                chatHistory: chatHistoryReceive
                            });
                        });
                    } else {//发送端
                        if (data.data?.content && data.data?.receiverId && userInfo.userId != data.data?.senderId) {//接收端 没有选择发送端会话时，处理消息接收详情
                            this.isReceiveSession(data.data);
                        }
                        let chatHistorySend = this.state.chatHistory.concat([]);
                        let chatIndex = chatHistorySend.findIndex(item => item.msgId == data.data.msgId)
                        if (chatHistorySend[chatIndex]?.sending) {
                            chatHistorySend[chatIndex].sending = 2
                            this.setState({
                                isClear: false,
                                chatHistory: chatHistorySend
                            }, () => {
                                this.getSessionList();
                            })
                        } else {
                            this.getSessionList();
                        }
                    }
                } else if (data?.msgType == 2) { //群聊
                    if (data.data?.content && data.data?.groupId == this.state.session?.groupId && data.data?.senderId != userInfo.userId) {//接收端接收消息
                        let chatHistoryReceive = this.state.chatHistory.concat([]);
                        chatHistoryReceive.push(data.data);
                        console.log('接收群聊消息', '_____', this.state.session.groupId == data.data?.groupId);
                        // this.setState({
                        //     chatHistory: chatHistoryReceive
                        // }, () => {
                        //     this.scrollToBottom();
                        //     this.isReceiveSession(data.data);
                        //     setTimeout(() => {
                        //         this.getSessionList();
                        //     }, 100);
                        // })
                        const executeMethods = async () => {
                            await this.scrollToBottom();
                            if (userInfo.userId != data.data.senderId) {
                                await this.isReceiveSession(data.data);
                            }
                            if (this.state.session?.groupId == data.data?.groupId) {
                                await this.setIsRead(this.state.session);
                            } else {
                                await this.getSessionList();
                            }
                            await new Promise((resolve) => setTimeout(resolve, 100)); // 模拟延迟操作
                        };

                        executeMethods().then(() => {
                            this.setState({
                                chatHistory: chatHistoryReceive
                            });
                        });
                    } else {//发送端
                        if (data.data?.content && data.data?.groupId && data.data?.senderId != userInfo.userId) {//群聊接收端接收消息
                            this.isReceiveSession(data.data);
                        }
                        let chatHistorySend = this.state.chatHistory.concat([]);
                        let chatIndex = chatHistorySend.findIndex(item => item.msgId == data.data.msgId)
                        if (chatHistorySend[chatIndex]?.sending) {
                            chatHistorySend[chatIndex].sending = 2
                            this.setState({
                                isClear: false,
                                chatHistory: chatHistorySend
                            }, () => {
                                this.getSessionList();
                            })
                        } else {
                            this.getSessionList();
                        }
                    }
                } else if (data?.msgType == 9) {//撤回
                    if (data.data?.msgId && data.data?.msgState == 0) {//接收端撤回消息
                        console.log('撤回消息', data);
                        let chatHistoryCallback = this.state.chatHistory.concat([]);
                        let index = chatHistoryCallback.findIndex(itm => itm.msgId === data?.data?.msgId);
                        chatHistoryCallback[index].msgState = 0;
                        setTimeout(() => {
                            this.setState({
                                isClear: false,
                                chatHistory: chatHistoryCallback,
                                showWithdraw: false,
                            }, () => {
                                this.scrollToBottom();
                            })
                        }, 300);
                    } else {
                        console.log('撤回', data);
                        let chatHistorySend = this.state.chatHistory.concat([]);
                        let index = chatHistorySend.findIndex(itm => itm.msgId === data?.data?.msgId);
                        chatHistorySend[index].msgState = 0;
                        setTimeout(() => {
                            this.setState({
                                isClear: false,
                                chatHistory: chatHistorySend,
                                // showWithdraw:false,
                            }, () => {
                                this.scrollToBottom();
                            })
                        }, 300);
                    }
                } else if (data?.msgType == 5) {//创建会话
                    console.log('创建会话', data);
                    this.getSessionList();
                } else if (data?.msgType == 6) {//置顶/取消置顶会话
                    console.log('/取消置顶会话', data);
                    message.success((this.state.isSeat ? '' : '取消') + '置顶成功');
                    this.setState({
                        menuVisible: false,
                    }, () => {
                        this.getSessionList();
                    })
                } else if (data?.msgType == 7) {//删除会话
                    message.success('移除会话成功');
                    this.setState({
                        menuVisible: false,
                        menuIndex: 0
                    }, () => this.getSessionList());
                } else if (data?.msgType == 11) {//屏蔽
                    console.log(this.state.isBlocking, '屏蔽会话', data);
                    message.success(this.state.isBlocking ? '屏蔽成功' : '取消屏蔽成功');
                    this.setState({
                        menuVisible: false
                    }, () => {
                        this.getSessionList();
                    })
                } else if (data?.msgType == 12) {//提醒、免打扰
                    message.success(this.state.isReminding ? '开启消息通知成功' : '设置免打扰成功');
                    this.setState({
                        menuVisible: false
                    }, () => {
                        this.getSessionList();
                    })
                } else if (data?.msgType == 13) {//消息已读
                    this.getSessionList();
                } else if (data?.msgType == 14) {//清空历史消息
                    message.success('清空历史消息成功');
                    this.setState({
                        menuVisible: false
                    }, () => {
                        this.getSessionList();
                        setTimeout(() => {
                            this.recentlyChat(this.state.session);
                        }, 300);
                    })
                }
                else if (data?.msgType == 15) {//禁言用户
                    let { groupInfo } = this.state
                    if (groupInfo.groupUserRole == 0) {
                        message.success('禁言用户成功');
                    }
                    this.setState({
                        openBannedPerson: false,
                        selectValue: '5分钟',
                        bannedAll: false,
                    }, () => {
                        setTimeout(() => {
                            this.getGroupBanned();
                        }, 200);
                    })
                } else if (data?.msgType == 16) {//禁言用户
                    let { groupInfo } = this.state
                    setTimeout(() => {
                        this.getGroupBanned();
                        if (groupInfo.groupUserRole == 0) {
                            message.success('解除用户禁言成功');
                        }
                    }, 1300);
                } else if (data?.msgType == 20) {//全群禁言设置可发言用户
                    this.setState({
                        cancelBannedPerson: false,
                        noBannedAll: false,
                    }, () => {
                        setTimeout(() => {
                            this.getGroupBanned();
                        }, 200);
                    })
                } else if (data?.msgType == 21) {//群内全员禁言后移除可发言成员
                    let { groupInfo } = this.state
                    setTimeout(() => {
                        this.getGroupBanned();
                        if (groupInfo.groupUserRole == 0) {
                            message.success('移除成功');
                        }
                    }, 1300);
                } else if (data?.msgType == 22) {//禁言用户/允许发言用户列表
                    let { userInfo } = this.state
                    let ban = data?.data;
                    let mutedMemberList = ban?.mutedMemberList || [];
                    let speakMemberList = ban?.speakMemberList || [];
                    let isSpeak = speakMemberList.some(item => item.memberId == userInfo.userId);
                    this.setState({
                        isBannedList: mutedMemberList,
                        speakMemberList,
                        allBanned: ban?.allMuted == 1 && !isSpeak ? true : false,
                    })
                } else if (data?.msgType == 23) {//	会话详情信息
                    console.log(data, 'json');
                    let groupUserList = data.data.memberList;
                    this.setState({
                        groupUserList,
                        bannedList: groupUserList,
                        noBannedList: groupUserList,
                        groupInfo: data.data,
                        // groupUserRole : 0群主，1管理员，2群员
                    }, () => {
                        setTimeout(() => {
                            this.getGroupBanned();
                        }, 100);
                    })
                }
            } else {
                if (data?.msgType == 1 || data?.msgType == 2) { //聊天
                    let chatHistorySend = this.state.chatHistory.concat([]);
                    if (data.data?.msgId) {
                        let chatIndex = chatHistorySend.findIndex(item => item.msgId == data.data.msgId)
                        chatHistorySend[chatIndex].sending = 0
                        // chatHistorySend[chatHistorySend.length - 1].sending = 0
                    } else if (data?.msg.includes('已被屏蔽')) {
                        chatHistorySend.push(
                            {
                                "clientType": 1,
                                "content": "<p>66</p>",
                                "createdTime": 1692776434000,
                                "msgId": "7100018970098532352",
                                "msgState": 1,
                                "receiverId": "lbladmin",
                                "senderId": "yangsen",
                                "signState": 0,
                                "sending": 2,
                                'isBlock': true
                            }
                        )
                    }

                    setTimeout(() => {
                        this.setState({
                            isClear: false,
                            chatHistory: chatHistorySend
                        })
                    }, 1500);
                }
                if (data.code == 3) {//关闭多页面，只保留一个聊天窗口
                    let userAgent = navigator.userAgent.toLowerCase(); // 获取浏览器用户代理字符串
                    let isSafari = /safari/.test(userAgent) && !/chrome/.test(userAgent); // 检测是否为 Safari 浏览器
                    if (isSafari) {
                        // Safari 浏览器关闭窗口的方式
                        window.open('', '_self').close();
                        window.opener = null;
                        window.open('', '_self').close();
                        window.open(sessionStorage.getItem('baseUrl'), '_self');
                    } else {
                        // 其他浏览器关闭窗口的方式
                        window.close();
                        window.opener = null;
                        window.open('', '_self');
                        window.open(sessionStorage.getItem('baseUrl'), '_self');
                    }
                    // if (this.state.isIframe == 1) {
                    // window.addEventListener('beforeunload', function () {
                    console.log('1234567890');
                    // 向父页面发送通知
                    window.parent.postMessage('closeChat', '*');
                    // });
                    // }
                }
                this.logError(data.msg);
            }
        };

        client.onclose = () => {
            console.log('WebSocket 连接已关闭');
            this.reconnectWebSocket(); // 连接关闭时重新建立连接
        };

        client.onerror = (error) => {
            console.error('WebSocket 错误', error);
            this.reconnectWebSocket(); // 连接错误时重新建立连接
        };

        this.client = client; // 保存WebSocket实例
    };

    //输出报错信息
    logError = (str) => {
        message.error(str, 3)
    }

    closeWebSocket = () => {
        if (this.client) {
            this.client.close(); // 关闭WebSocket连接
        }
    };
    //断线重连
    reconnectWebSocket = () => {
        console.log('断线重连');
        setTimeout(() => {
            this.connectWebSocket(); // 重新建立连接
        }, 60000); // 60秒后重新调用登录函数
    };

    //检测消息是否全为空格
    isStringEmpty = (str) => {
        // 去除 HTML 标签
        // var content = str.replace(/<(.*?)>/g, '');
        // 匹配空标签的正则表达式
        const regex = /<(\w+)\s*>(\s|&nbsp;|<br\s*\/?>)*<\/\1>/g;

        // 使用 replace() 方法将匹配到的空标签替换为空字符串
        let content = str.replace(regex, '');

        // 将 &nbsp; 替换为空格
        content = content.replace(/(&nbsp;|\s)+/g, ' ');

        // 去除空白字符
        content = content.trim();

        // 判断字符串是否为空
        return content.length === 0;
    }

    // 去除标签
    getStr = (str) => {
        // 匹配空标签的正则表达式
        str = decodeURI(str);
        return str.replace(/<[^>]*>/g, '');
    }

    //单聊/群聊——发送消息
    sendPrivateMessage = (type, msg) => {
        let {
            chatContent,
            token,
            session,
            chatHistory,
            // receiverId,
            userInfo,
        } = this.state
        console.log(userInfo, 'chatContent', chatContent);
        chatHistory = chatHistory.concat([]);
        if ((chatContent == '' || this.isStringEmpty(chatContent)) && !msg) {
            // message.warn('不能发送空消息！')
            // this.setState({
            //     clear: true,
            // })
            return;
        }
        let FlakeIdGen = require('flake-idgen');
        let intformat = require('biguint-format');

        // 创建一个 FlakeIdGen 实例
        // let flakeIdGen = new FlakeIdGen();
        let flakeIdGen = new FlakeIdGen({ machine: 1, datacenter: 1 });
        let regex = /style="[^"]*"/g; // 匹配 style 属性及其值
        // 使用雪花算法生成 18 位的雪花ID
        let flakeId = intformat(flakeIdGen.next(), 'dec');
        let sentTime = dayjs().format();
        console.log(userInfo)
        let messageData = {
            msgType: session?.receiverId ? 1 : 2,
            clientType: '1',
            token,
            data: {
                receiverId: session.receiverId, // 替换为实际的接收者ID
                content: chatContent.replace(regex, ''), // 替换为实际的消息内容
                sessionId: session.sessionId,
                createdTime: sentTime,
                schoolId: userInfo.schoolId,
                senderId: userInfo.userId,
                sending: 1,//1正在发送，2发送完成,0发送失败
                msgId: flakeId,
                groupId: session.groupId,
                groupName: session.groupName,
                isJustSend: 1,
                avatarPath: userInfo.photoPath,
                senderName: userInfo.userName,
            }
        };
        if (session?.groupId) {
            delete messageData.data.receiverId;
        } else {
            delete messageData.data.groupId;
            delete messageData.data.groupName;
            // delete messageData.data.avatarPath;
        }
        // 每次只显示其中一条刚发布的
        let isJustSendIndex = chatHistory.findIndex(item => item?.isJustSend === 1);
        if (isJustSendIndex > -1) {
            delete messageData.data.isJustSend;
        }
        console.log('type', type);

        if (type == 'img') {
            chatHistory[chatHistory.length - 1] = messageData.data
        } else if (type == 'retry' && msg) {
            msg.sending = 1;
            messageData.data = msg;
        } else {
            chatHistory.push(messageData.data)
        }
        setTimeout(() => {
            let failArr = this.state.chatHistory.concat([]);
            let currentTime = Date.now();
            failArr.forEach(item => {
                const diffInSeconds = Math.abs((currentTime - new Date(item.createdTime)) / 1000);
                // 超过八秒未返回或者没有变为已发送状态的信息，修改为发送失败
                if (diffInSeconds > 8 && item.sending == 1) {
                    item.sending = 0
                }
            })

            this.setState({
                chatHistory: failArr,
            })
        }, 8000);


        console.log(chatHistory, 'messageData', messageData);
        this.setState({
            isClear: true,
            chatHistory,
            isSend: true,
            // clear:true,
            chatContent: '',
        }, () => {
            this.scrollToBottom();
            this.client.send(JSON.stringify(messageData)); // 发送单聊消息
        })

    };

    // 创建会话
    createSession = () => {
        let {
            userInfo,
            token,
            receiverId,
            receiverName,
            isGroup,
            groupId,
            groupName,
            sessionList,
            receiverAvatarPath,
        } = this.state

        if (isGroup != 1 && (!receiverId || !receiverName)) {
            this.getSessionList();
            // message.warn('接收者不存在！')
            // this.setState({
            //     notReceiver: true,
            // })
            // if(sessionList.length>0){
            //     this.chooseChatObj(sessionList[0]);
            // }
            return;
        }
        let createData = {
            msgType: 5,
            clientType: '1',
            token,
            data: {
                sessionType: isGroup == 1 ? '2' : '1',
                // senderId: userInfo.userId,
                receiverId,
                receiverName,
                receiverAvatarPath,
                groupId,
                groupName,
                schoolId: userInfo.schoolId,
            }
        };
        if (isGroup == 1) {
            delete createData.data.receiverId;
            delete createData.data.receiverName;
            delete createData.data.receiverAvatarPath;
        } else {
            delete createData.data.groupId;
            delete createData.data.groupName;
        }
        console.log('创建会话', createData);
        this.client.send(JSON.stringify(createData));
    }

    //获取个人会话列表
    getSessionList = () => {
        let {
            userInfo,
            token,
            pageNum,
            pageSize,
            receiverId,
            firstNum,
            groupId,
            keyword,
        } = this.state
        let sessionData = {
            msgType: 4,
            clientType: '1',
            token,
            data: {
                keyword, // 会话对应的接收者名称
                // pageNum,
                // pageSize,
            }
        };
        console.log('会话列表参数', sessionData);
        this.setState({
            firstNum: firstNum + 1
        }, () => {
            this.client.send(JSON.stringify(sessionData));
        })
    }

    //置顶/取消置顶会话
    manageSeat = (e, item) => {
        e.stopPropagation();
        e.preventDefault();
        let { token } = this.state
        let topSession = {
            msgType: 6,
            clientType: '1',
            token,
            data: {
                sessionId: item.sessionId,
                seat: item.seat == '0' ? 1 : 0,
                sessionType: item?.receiverId ? 1 : 2
            }
        };
        console.log('topSession', topSession);
        this.setState({
            isSeat: item.seat == '0' ? true : false
        }, () => {
            this.client.send(JSON.stringify(topSession));
        })
    }

    // 删除会话
    delSession = (e, item) => {
        e.stopPropagation();
        e.preventDefault();
        let { token, receiverId, groupId } = this.state
        console.log('删除会话', item);
        let delSession = {
            msgType: 7,
            clientType: '1',
            token,
            data: {
                sessionId: item.sessionId,
            }
        };
        console.log('delSession', delSession);
        if (item?.receiverId && item?.receiverId === receiverId) {
            sessionStorage.setItem('receiverId', '')
        } else if (item?.groupId && item?.groupId === groupId) {
            sessionStorage.setItem('groupId', '')
        }

        this.client.send(JSON.stringify(delSession));
    }

    // 单个会话最近消息记录
    recentlyChat = (item) => {
        let { token, chatHistory, pageNum, isFetching } = this.state
        console.log('单个会话最近消息记录',);
        if (isFetching || !item?.sessionId) {
            return; // 如果正在获取聊天记录，则不执行后续逻辑
        }
        let recentlyHistory = {
            msgType: 8,
            clientType: '1',
            token,
            data: {
                sessionId: item?.sessionId,
                sessionType: item?.groupId ? '2' : '1',
                pageNum,
                pageSize: 20
            }
        };
        this.setState({ isFetching: true }, () => {
            console.log('recentlyHistory', recentlyHistory);
            this.client.send(JSON.stringify(recentlyHistory));
        });
    }

    // 单个会话最近消息（历史）记录
    historyMessage = () => {
        let { token, session, pageHistoryNum, pageHistorySize, isFetching, historyDate, onlyViewPerson } = this.state
        console.log(isFetching, '单个会话最近历史记录', pageHistoryNum);
        if (isFetching) return;
        let recentlyHistory = {
            msgType: 8,
            clientType: '1',
            token,
            data: {
                sessionId: session.sessionId,
                sessionType: session?.groupId ? '2' : '1',
                pageNum: pageHistoryNum,
                pageSize: pageHistorySize,
                day: historyDate,
                onlyShowOther: onlyViewPerson,
            }
        };
        
        this.setState({ openChatHistory: true, isFetching: true }, () => {
            console.log('recentlyHistory', recentlyHistory);
            this.client.send(JSON.stringify(recentlyHistory));
        });
    }


    // 接收端接收到消息，返回给后台数据，表明已经收到该消息
    isReceiveSession = (item) => {
        // let { token, userInfo, session } = this.state
        // console.log('返回收到消息', item);
        // let receiveSession = {
        //     msgType: 100,
        //     clientType: '1',
        //     token,
        //     data: {
        //         msgId: item.msgId,
        //         clientType: 1,
        //         schoolId: userInfo.schoolId,
        //         receiverId: item?.senderId,
        //         // receiverId: userInfo?.user,
        //         receiverName: session?.receiverName,
        //         // receiverName: session?.receiverName,
        //         groupId: item?.groupId,
        //         groupName: session?.groupName,
        //         sessionType: session?.receiverName ? 1 : 2,
        //     }
        // };
        // if (item?.groupId) {
        //     delete receiveSession.data.receiverId;
        //     delete receiveSession.data.receiverName;
        // } else {
        //     delete receiveSession.data.groupId;
        //     delete receiveSession.data.groupName;
        // }
        // console.log('receiveSession', receiveSession);
        // this.client.send(JSON.stringify(receiveSession));
        let { token, userInfo, session, sessionList } = this.state
        console.log('返回收到消息', item);
        let sessionInfo = null;
        if (item?.groupId) {
            sessionInfo = sessionList.find(session => session?.groupId == item?.groupId)
        } else {
            sessionInfo = sessionList.find(session => session?.receiverId == item?.senderId)
        }
        let receiveSession = {
            msgType: 100,
            clientType: '1',
            token,
            data: {
                msgId: item.msgId,
                clientType: 1,
                schoolId: userInfo.schoolId,
                receiverId: item?.senderId,
                receiverName: sessionInfo?.receiverName || item?.senderName,
                receiverAvatarPath: item?.senderAvatarPath || item?.avatarPath,
                // receiverId: userInfo.userId,
                // receiverName: userInfo.userName,
                groupId: item?.groupId || sessionInfo?.groupId,
                groupName: item?.groupName || sessionInfo?.groupName,
                sessionType: item?.groupId != undefined ? 2 : 1,
            }
        };
        // if (item?.groupId) {
        //     delete receiveSession.data.receiverId;
        //     delete receiveSession.data.receiverName;
        // } else {
        //     delete receiveSession.data.groupId;
        //     delete receiveSession.data.groupName;
        // }
        console.log('receiveSession', receiveSession);
        this.client.send(JSON.stringify(receiveSession));
    }

       // 撤回消息
       recallChat = (item) => {
        let { token, chatHistory, session, groupInfo } = this.state
        console.log(item, '撤回消息', groupInfo.groupUserRole);
        let recallChatItem = {
            msgType: 9,
            clientType: '1',
            token,
            data: {
                sessionType: session?.receiverId ? 1 : 2,
                msgId: item?.msgId,
                receiverId: item?.receiverId || item?.groupId,
                groupUserRole: groupInfo && groupInfo.groupUserRole !== undefined ? groupInfo.groupUserRole : 2,
                senderId: item?.senderId,
            }
        };
        console.log('recallChatItem', recallChatItem);
        let chatArr = chatHistory.concat([]);
        let index = chatArr.findIndex(itm => itm.msgId === item.msgId);
        chatArr[index].isRecall = 1;//设置撤回

        this.client.send(JSON.stringify(recallChatItem));
    }

    // 拉取离线消息——登录完就调用
    pullOfflineMessage = (item) => {
        let { token, chatHistory, session } = this.state
        console.log('拉取离线消息',);
        let offlineMessage = {
            msgType: 10,
            clientType: '1',
            token,
            data: {
                // sessionType: session?.receiverId ? 1 : 2,
                // msgId: item?.msgId,
                // receiverId: item?.receiverId || item?.groupId
            }
        };
        console.log('offlineMessage', offlineMessage);

        this.client.send(JSON.stringify(offlineMessage));
    }

    // 屏蔽消息
    maskMessage = (e, item, type) => {
        if (e) {
            e.stopPropagation();
            e.preventDefault();
        }
        let { token, blockPerson } = this.state
        console.log(' 屏蔽消息', item);
        let maskSession = {
            msgType: 11,
            clientType: '1',
            token,
            data: {
                sessionId: item.sessionId,
                block: (item.block == 1 && type == 'list') || (!blockPerson && type == 'set') ? 0 : 1,
            }
        };
        this.setState({
            isBlocking: (item.block == 1 && type == 'list') || (!blockPerson && type == 'set') ? false : true,
        }, () => this.client.send(JSON.stringify(maskSession)))
    }

    // 消息免打扰
    noDisturbMessage = (e, item, type) => {
        if (e) {
            e.stopPropagation();
            e.preventDefault();
        }
        let { token, disturbing } = this.state
        console.log(' 消息免打扰', item);
        let disturbSession = {
            msgType: 12,
            clientType: '1',
            token,
            data: {
                sessionId: item.sessionId,
                remind: (item.remind == 1 && type == 'list') || (disturbing && type == 'set') ? 0 : 1,
            }
        };
        this.setState({
            isReminding: (item.remind == 1 && type == 'list') || (disturbing && type == 'set') ? false : true,
        }, () => this.client.send(JSON.stringify(disturbSession)))
    }

    // 已读设置
    setIsRead = (item) => {
        let { token } = this.state
        console.log(' 已读设置', item);
        let isReadSession = {
            msgType: 13,
            clientType: '1',
            token,
            data: {
                sessionType: item.sessionType,
                receiverId: item?.receiverId,
                groupId: item?.groupId,
            }
        };
        if (item?.groupId) {
            delete isReadSession.data.receiverId;
        } else {
            delete isReadSession.data.groupId;
        }
        this.client.send(JSON.stringify(isReadSession))
    }

    // 清空历史消息
    clearHistoryMsg = (e, item, type) => {
        if (e) {
            e.stopPropagation();
            e.preventDefault();
        }
        let { token } = this.state
        console.log(' 清空历史消息', item);
        this.setState({
            isBtnDel: type === 'btn' ? true : false,
        }, () => {
            let clearMsg = {
                msgType: 14,
                clientType: '1',
                token,
                data: {
                    sessionId: item.sessionId,
                }
            };
            this.client.send(JSON.stringify(clearMsg))
        })
    }

    //选择聊天列表内对象
    chooseChatObj = (item) => {
        console.log('item1', item);
        if (!item) return;
        this.setState({
            session: item,
            pageNum: 1,
            isTop: false,
            isFetching: false,
            pageHistoryNum: 1,
            demonstrationValue: new Date(),
            isChoosed: true,
        }, () => {
            if (item?.receiverId) {
                this.setState({
                    allBanned: false,
                    groupInfo: {},
                }, () => {
                    this.getUserInfo(item?.receiverId, 'obj')
                })
            }
            if (item?.unReadCount > 0) {
                this.setIsRead(item);
            }
            if (item?.groupId) {
                this.getSessionInfo(item?.groupId);
            }
            setTimeout(() => {
                this.recentlyChat(item);
            }, 200);
        })
    }

    //获取指定用户基本信息
    getUserInfo = (userId, type) => {
        if (userId == undefined || !userId) return;
        let { userInfo, userObj, schoolInfo } = this.state
        if (userObj?.userId == userId) {
            if (type == 'user') {
                this.openUserLgDrawer(userObj);
            }
            return;
        }
        getData('/api/commons/school/user/search/one', {
            schoolId: userInfo.schoolId,
            userId,
        }).then(data => {
            return data.json()
        }).then(json => {
            getData1(schoolInfo.baseUrl + 'edu-office-platform/api/contact/detail', {
                eduId: userInfo.schoolId,
                userId,
                userType: json.data.userType,
            }).then(data => {
                return data.json()
            }).then(json => {
                console.log(type, 'json', json);
                if (type == 'obj') {
                    this.setState({
                        userObj: json.data,
                    })
                } else {
                    this.openUserLgDrawer(json.data);
                }
            })
        })
    }

    //打开用户信息
    openUserLgDrawer = (item) => {
        console.log('item1', item);
        this.setState({
            openUserInfo: item ? item : null
        }, () => {
            this.setState({
                openUserVisible: !this.state.openUserVisible,
            })
        })
    }

    //打开聊天设置
    openSetting = () => {
        let { session } = this.state
        console.log('session', session);
        this.setState({
            blockPerson: session.block == 0 ? false : true,
            disturbing: session.remind == 1 ? false : true,
            userSearch: false,
            groupUserKeyword: '',
            pageHistoryNum: 1
        }, () => {
            this.setState({
                openSettingVisible: !this.state.openSettingVisible,
            })
        })
    }

    //关闭历史记录
    closeChat = () => {
        this.setState({
            openChatHistory: false,
            openSettingVisible: false,
            onlyViewPerson: false,
            historyDate: dayjs().format('YYYY-MM-DD'),
            // demonstrationValue: new Date(),
            // pageHistoryNum: 1,
        })
    }
        // 关闭禁言窗口
    closeBanned = (type) => {
        if (type === 'bannedPop') {
                this.setState({
                    openBanned: false,
                })
            } else if (type === 'bannedPer') {
                this.setState({
                    openBannedPerson: false,
                    bannedSelectList: [],
                    bannedAll: false,
                })
            } else if (type === 'bannedPerClose') {
                this.setState({
                    cancelBannedPerson: false,
                    bannedSelectCloseList: [],
                    noBannedAll: false,
                })
            }
        }
        // 打开禁言窗口
        openBannedPop = (type) => {
            if (type === 'bannedPop') {
                this.setState({
                    openBanned: true,
                }, () => {
                    setTimeout(() => {
                        this.getGroupBanned();
                    }, 200);
                })
            } else if (type === 'bannedPer') {
                this.setState({
                    openBannedPerson: true,
                })
            } else if (type === 'bannedPerClose') {
                this.setState({
                    cancelBannedPerson: true,
                })
            }
        }
    //屏蔽与免打扰
    blockAndDisturbing = (type, boolean) => {
        console.log('type, boolean', type, boolean);
        let {
            session,
            token,

        } = this.state
        if (type == 'block') {
            this.setState({
                blockPerson: !boolean
            }, () => {
                this.maskMessage('', session, 'set');
            })
        } else if (type == 'disturbing') {
            this.setState({
                disturbing: !boolean
            }, () => {
                this.noDisturbMessage('', session, 'set')
            })
        } else if (type == 'allBanned') {//全员禁言
            this.setState({
                allBanned: !boolean
            }, () => {
                let bannedAllSession = {
                    msgType: 17,
                    clientType: '1',
                    token,
                    data: {
                        groupId: session.groupId,
                        allMuted: !boolean ? 1 : 0,
                    }
                };
                console.log('bannedAllSession', bannedAllSession);
                this.client.send(JSON.stringify(bannedAllSession));
            })
        } else if (type == 'canEmoji') {
            this.setState({
                canEmoji: !boolean
            }, () => {
                let canEmojiSession = {
                    msgType: 18,
                    clientType: '1',
                    token,
                    data: {
                        groupId: session.groupId,
                        allowEmoji: !boolean ? 1 : 0,
                    }
                };
                console.log('canEmojiSession', canEmojiSession);
                // this.client.send(JSON.stringify(canEmojiSession));
            })
        } else if (type == 'canText') {
            this.setState({
                canText: !boolean
            }, () => {
                let canTextSession = {
                    msgType: 18,
                    clientType: '1',
                    token,
                    data: {
                        groupId: session.groupId,
                        allowWord: !boolean ? 1 : 0,
                    }
                };
                console.log('canTextSession', canTextSession);
                // this.client.send(JSON.stringify(canTextSession));
            })
        }
    }
    //仅看对方
    viewPerson = () => {
        this.setState({
            pageHistoryNum: 1,
            onlyViewPerson: !this.state.onlyViewPerson
        }, () => this.historyMessage())
    }

    //切换页码
    changePage = (page) => {
        console.log('page', page);
        this.setState({
            pageHistoryNum: page
        }, () => {
            this.historyMessage();
        })
    }

    //选择日期
    selectDate = (time) => {
        let date = time && dayjs(time).format('YYYY-MM-DD');
        console.log(date, 'time', time);
        this.setState({
            historyDate: date ? date : null,
            demonstrationValue: time,
            pageHistoryNum: 1,
        }, () => {
            this.historyMessage();
        })
    }

    //打开更多菜单
    openMoreMenu = (e, item, index) => {
        console.log('item1', item);
        e.stopPropagation();
        e.preventDefault();

        this.setState({
            menuVisible: true,
            menuIndex: index
        })
    }

    //关闭更多菜单
    closeMoreMenu = () => {
        this.setState({
            menuVisible: false,
            menuIndex: null
        })
    }

   //是否展示消息菜单
   openRevoke = (time, index) => {
    // console.log('time', time);
    let { groupInfo } = this.state
    if (!time) return;
    let currentTime = dayjs();
    let diffMinutes = currentTime.diff(time, 'minute');
    // console.log('diffMinutes:', diffMinutes);
    this.setState({
        showTime: true,
        showTimeIndex: index,
    })
    if (diffMinutes < 2) {
        this.setState({
            isShowWithdraw: true,
            showIndex: index,
        })
    } else {
        this.setState({
            isShowWithdraw: groupInfo?.groupUserRole == 0 ? true : false,
            showWithdraw: false,
            showIndex: groupInfo?.groupUserRole == 0 ? index : 0,
        })
    }
}
    openRevoke1 = () => {
        this.setState({
            showWithdraw: true,
        })
    }
    closeRevoke = () => {
        this.setState({
            isShowWithdraw: false,
            showWithdraw: false,
            showTime: false,
        })
    }
    closeRevoke1 = () => {
        this.setState({
            showWithdraw: false,
        })
    }
    //重新编辑
    recallMessage = (item) => {
        console.log('item', item);
        this.setState({
            chatContent: item.content,
            isReEdit: true,
        })
    }

    getSize = (size) => {
        if (size < 1024) {
            return size + 'B'
        } else if (size < 1024 * 1024) {
            return (size / 1024).toFixed(1) + 'KB'
        } else if (size < 1024 * 1024 * 45) {
            return (size / 1024 / 1024).toFixed(1) + 'MB'
        }
    }

    // 重发
    alertAQuestion2 = (item) => {
        let alert = lgAlert.show({
            duration: 0,
            content: '是否重新发送该条消息？',
            //   description: '点击"确定"将删除该类型及该类型下的全部公告。',
            isShowCloseBtn: true,
            tipType: 'warning',
            // tipSize: 'small',
            tipSize: 'big',
            tipMouldType: 'A',
            confirmText: "重新发送",
            closeText: "取消",
            showCover: true,
            coverZIndex: 1000,
            coverOpacity: 0.25,
            position: { xAxis: '50%', yAxis: '35%', showDirection: 'center', xOffset: '-50%' },
            onConfirm: () => {
                this.sendPrivateMessage('retry', item);
                lgAlert.close(alert.index);
            }
        });
        console.log('alertAQuestion2', item);

    }

    // 预览图片
    openPreview = (event) => {
        event.preventDefault(); // 阻止浏览器默认的滚动行为
        const target = event.target;
        // 筛选出 <img> 元素
        if (target.tagName === 'IMG') {
            const imgUrl = target.getAttribute('src'); // 获取图片链接
            const imageContainer = document.createElement("div");
            imageContainer.innerHTML = '<img src="' + imgUrl + '">';
            const viewer = new Viewer(imageContainer, {
                toolbar: {
                    zoomIn: 4,
                    zoomOut: 4,
                    oneToOne: 4,
                    reset: 4,
                    prev: { show: false, size: 'large' },
                    play: { show: true, size: 'large' },
                    next: { show: false, size: 'large' },
                    rotateLeft: { show: true, size: 'large' },
                    rotateRight: { show: true, size: 'large' },
                    flipHorizontal: { show: true, size: 'large' },
                    flipVertical: { show: true, size: 'large' }
                }
            });
            viewer.show();
            // Zmage.browsing({
            //     src: imgUrl,
            //     backdrop: "rgba(0,0,0,0.5)",
            //     position: "center",
            //     size: "contain"
            // }); // 打开预览窗口
        }
    };

    // 判断是否到达聊天记录的顶部
    handleScroll = (e) => {
        let { pageNum, session, isTop, isFetching } = this.state
        let scrollTop = e.target.scrollTop;
        const topOffset = 450; // 自定义的顶部偏移值
        console.log(scrollTop, 'scrollTop',);
        console.log(document.body.clientWidth)
        this.setState({
            screenWidth: document.body.clientWidth
        })
        if (scrollTop === 0 || scrollTop <= topOffset) {
            console.log('已到达顶部');
            if (isTop || isFetching) return;
            this.setState({
                pageNum: pageNum + 1
            }, () => this.recentlyChat(session))
        }
    }

    calculateTimeDifference = (givenTimeStr) => {
        let givenTime = new Date(givenTimeStr);
        let currentTime = new Date();

        let timeDifference = currentTime.getTime() - givenTime.getTime();
        let minutesDifference = Math.floor(timeDifference / 60000); // 转换为分钟
        if (minutesDifference === 0) {
            return "刚刚";
        } else if (minutesDifference < 60) {
            return `${minutesDifference}分钟前`;
        } else if (minutesDifference < 1440) {
            let hoursDifference = Math.floor(minutesDifference / 60); // 转换为小时
            return `${hoursDifference}小时前`;
        } else {
            return `${dayjs(givenTimeStr).format('YYYY-MM-DD HH:mm')}`;
        }

        // 其他情况下返回原始分钟差距
        // return `${minutesDifference}分钟前`;
    }
    // 时间返回函数
    formatTime = (timestamp) => {
        let targetDate = dayjs(timestamp);
        let currentDate = dayjs();

        if (targetDate.isSame(currentDate, 'day')) {
            // 如果是今天，返回时分
            return targetDate.format('HH:mm');
        } else {
            // 如果不是今天，返回月日
            return targetDate.format('MM-DD');
        }
    };
    // 嵌入页面关闭功能
    closeIframe = () => {
        // 向父页面发送通知
        window.parent.postMessage('closeChat', '*');
    }

    //获取聊天群组人员列表
    getGroupInfo = (groupId) => {
        getData('/api/chat/group/member/list', {
            groupId
        }).then(data => {
            return data.json()
        }).then(json => {
            let data = json.data.concat([]);
            console.log(data, 'json', json);
            this.setState({
                groupUserList: json.data,
                bannedList: data,
                noBannedList: data,
            })
        })
    }

    searchGroupUser = () => {
        let { groupUserList, groupUserKeyword } = this.state
        // 使用 filter 方法进行模糊搜索
        let filteredUsers = groupUserList.filter(user => user.memberName.includes(groupUserKeyword));
        this.setState({
            searchGroupList: filteredUsers,
        })
    }
    searchBannedUser = () => {
        let { bannedList, bannedKeyword, } = this.state
        if (bannedKeyword == '') return;
        // 使用 filter 方法进行模糊搜索
        let filteredUsers = bannedList.filter(user => user.memberId.includes(bannedKeyword) || user.memberName.includes(bannedKeyword));
        this.setState({
            searchBannedList: filteredUsers,
        })
    }
    searchNoBannedUser = () => {
        let { noBannedList, noBannedKeyword, } = this.state
        if (noBannedKeyword == '') return;
        // 使用 filter 方法进行模糊搜索
        let filteredUsers = noBannedList.filter(user => user.memberId.includes(noBannedKeyword) || user.memberName.includes(noBannedKeyword));
        this.setState({
            searchNoBannedList: filteredUsers,
        })
    }
    // 选择禁言的用户
    selectBanned = (item, type) => {
        let { bannedSelectList, bannedSelectCloseList, isBannedList, speakMemberList, bannedList, noBannedList } = this.state;
        if (type === 'banned') {
            let isAll = false;
            let index = bannedSelectList.findIndex((user) => user.memberId === item.memberId);
            if (index !== -1) {
                // 用户已存在于 bannedSelectList 中，进行删除操作
                bannedSelectList.splice(index, 1);
            } else {
                // 用户不存在于 bannedSelectList 中，进行插入操作
                bannedSelectList.push(item);
            }
            if (bannedSelectList.length === bannedList.length - 1 - isBannedList.length) {
                isAll = true
            }
            // 更新 state 中的 bannedSelectList
            this.setState({
                bannedSelectList: [...bannedSelectList],
                bannedAll: isAll
            });
        } else {
            let isAll = false;
            let index = bannedSelectCloseList.findIndex((user) => user.memberId === item.memberId);
            if (index !== -1) {
                // 用户已存在于 bannedSelectCloseList 中，进行删除操作
                bannedSelectCloseList.splice(index, 1);
            } else {
                // 用户不存在于 bannedSelectCloseList 中，进行插入操作
                bannedSelectCloseList.push(item);
            }
            if (bannedSelectCloseList.length === noBannedList.length - 1 - speakMemberList.length) {
                isAll = true
            }

            // 更新 state 中的 bannedSelectCloseList
            this.setState({
                bannedSelectCloseList: [...bannedSelectCloseList],
                noBannedAll: isAll,
            });
        }
    }

    // 禁言时间选择
    timeSelect = (item) => {
        console.log("选择的item:", item);
        this.setState({
            selectValue: item.text,
        })
    }

    // 确定禁言用户
    setBanned = () => {
        let { bannedSelectList, token, session, selectValue } = this.state
        console.log(selectValue, 'bannedSelectList', bannedSelectList);
        if (bannedSelectList.length === 0) {
            message.warn('请先选择禁言成员！');
            return;
        }
        let durationMap = {
            '5分钟': 300000,
            '1小时': 3600000,
            '1天': 86400000,
            '7天': 604800000,
            '30天': 2592000000
        };
        let mutedMemberList = bannedSelectList.map(item => {
            let duration = durationMap[selectValue];
            let endTime = Date.now() + duration;
            return {
                memberId: item.memberId,
                memberName: item.memberName,
                endTime: dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
            }
        })
        let bannedSession = {
            msgType: 15,
            clientType: '1',
            token,
            data: {
                groupId: session.groupId,
                mutedMemberList,
            }
        };
        console.log('bannedSession', bannedSession);
        this.setState({
            bannedSelectList: [],
        }, () => this.client.send(JSON.stringify(bannedSession)))
    }

    // 群禁言设置详情信息
    getGroupBanned = () => {
        let { token, session } = this.state
        let groupBannedSession = {
            msgType: 22,
            clientType: '1',
            token,
            data: {
                groupId: session.groupId,
            }
        };
        console.log('groupBannedSession', groupBannedSession);
        this.client.send(JSON.stringify(groupBannedSession))
    }

    // 群内解禁禁言成员
    relieveBanned = (user) => {
        let { token, session } = this.state
        message.loading('解除禁言中~');
        let relieveBannedSession = {
            msgType: 16,
            clientType: '1',
            token,
            data: {
                groupId: session.groupId,
                memberId: user.memberId
            }
        };
        this.client.send(JSON.stringify(relieveBannedSession))
    }

    // 群禁言后添加可发言成员
    setCanSpeak = () => {
        let { bannedSelectCloseList, token, session } = this.state
        if (bannedSelectCloseList.length === 0) {
            message.warn('请先选择可发言成员！');
            return;
        }
        let speakMemberList = bannedSelectCloseList.map(item => {
            return {
                memberId: item.memberId,
                memberName: item.memberName,
            }
        })
        let speakSession = {
            msgType: 20,
            clientType: '1',
            token,
            data: {
                groupId: session.groupId,
                speakMemberList,
            }
        };
        console.log('speakSession', speakSession);
        this.setState({
            bannedSelectCloseList: [],
        }, () => this.client.send(JSON.stringify(speakSession)))
    }

    // 群禁言后移除可发言成员
    removeSpeak = (user) => {
        let { token, session } = this.state
        message.loading('移除中~');
        let removeSpeakSession = {
            msgType: 21,
            clientType: '1',
            token,
            data: {
                groupId: session.groupId,
                memberId: user.memberId
            }
        };
        this.client.send(JSON.stringify(removeSpeakSession))
    }

    // 计算禁言解除时间
    getTimeDiff = (timestamp) => {
        const currentDate = dayjs(); // 当前时间
        const targetDate = dayjs(timestamp); // 时间戳转换为日期

        if (currentDate.isAfter(targetDate)) {
            return '禁言已结束';
        }

        // 计算时间差
        let diff = Math.abs(targetDate.diff(currentDate));

        const days = Math.floor(diff / (24 * 60 * 60 * 1000));
        const hours = Math.floor(diff / (60 * 60 * 1000)) % 24;
        const minutes = Math.floor(diff / (60 * 1000)) % 60;

        let timeDiffStr = '';
        if (days > 0) {
            timeDiffStr += `${days}天`;
        }
        if (hours > 0) {
            timeDiffStr += `${hours}小时`;
        }
        if (minutes > 0) {
            timeDiffStr += `${minutes}分钟`;
        }

        if (timeDiffStr === '') {
            timeDiffStr = '不到1分钟';
        } else {
            timeDiffStr += '后解除禁言';
        }
        return timeDiffStr;
    }

    // 全选
    allSelect = (type) => {
        let { bannedList, noBannedList, isBannedList, speakMemberList, userInfo, bannedAll, noBannedAll } = this.state;

        if (type === 'banned') {
            let filteredBannedSelectCloseList = [];
            if (!bannedAll) {
                filteredBannedSelectCloseList = bannedList.filter(member => !isBannedList.some(item => item.memberId === member.memberId) && member.memberId !== userInfo.userId);
            }
            this.setState({
                bannedSelectList: filteredBannedSelectCloseList,
                bannedAll: !bannedAll,
            });
        } else {
            // 生成新的数组，保留原有数组中满足条件的数据
            let filteredBannedSelectCloseList = [];
            if (!noBannedAll) {
                filteredBannedSelectCloseList = noBannedList.filter(member => !speakMemberList.some(speakMember => speakMember.memberId === member.memberId) && member.memberId !== userInfo.userId);
            }

            this.setState({
                bannedSelectCloseList: filteredBannedSelectCloseList,
                noBannedAll: !noBannedAll,
            });
        }
    }
    // 会话详情信息
    getSessionInfo = () => {
            let { token, session } = this.state
            let sessionInfo = {
                msgType: 23,
                clientType: '1',
                token,
                data: {
                    sessionId: session.sessionId
                }
            };
            this.client.send(JSON.stringify(sessionInfo))
        }

    render() {
        let {
            loading,
            openSettingVisible,
            openChatHistory,
            isIframe,
            blockPerson,
            disturbing,
            onlyViewPerson,
            pageNum,
            historyDate,
            demonstrationValue,
            isClear,
            menuVisible,
            menuIndex,
            keyword,
            sessionList,
            session,
            chatHistory,
            openUserInfo,
            openOtherUserInfo,
            openUserVisible,
            showTime,
            showWithdraw,
            isShowWithdraw,
            showIndex,
            showTimeIndex,
            userInfo,
            isReEdit,
            isSearch,
            selectedFile,
            notReceiver,
            historyMessageList,
            pageHistoryNum,
            pageHistorySize,
            totalNum,
            userObj,
            token,
            isDownload,
            downloadPercent,
            clear,
            isFull,
            groupUserList,
            groupUserItem,
            groupUserKeyword,
            userSearch,
            searchGroupList,
            screenWidth,
            openBanned,
            isBannedList,
            allBanned,
            speakMemberList,
            groupInfo,
            openBannedPerson,
            cancelBannedPerson,
            bannedKeyword,
            bannedSearch,
            noBannedKeyword,
            noBannedSearch,
            bannedAll,
            searchBannedList,
            bannedSelectList,
            bannedList,
            selectValue,
            timeList,
            noBannedAll,
            bannedSelectCloseList,
            searchNoBannedList,
            noBannedList
        } = this.state

        // console.log('groupInfo', groupInfo)
        let userType = userObj?.userType;
        console.log('userType', userType);

        let $this = this;
        const uploadFiles = {
            action: window._chatBasicProxy + 'api/commons/file/batch/upload?modelName=chat-' + userInfo.userId + '&sysId=460',
            accept: 'file*/',
            multiple: false,
            name: 'files',
            headers: {
                Authorization: getQueryVariable('lg_tk') || sessionStorage.getItem('token'),
            },
            onStart(file) {
                $this.setState({
                    loading: true
                })
                console.log('onStart', file, file.name);
            },
            onSuccess(ret) {
                let url = ret.data[0].url.replace(/ /g, ""), content = '', data = ret.data[0];
                if (data.type == '1') {//文件
                    content = `<div class='upload-div'>
                    <div class='uploadfile-div'><i class='uploadfile-icon uploadfile-icon-${data.fileName.split('.').pop()}'></i>
                    <div class='uploadfile-div-right'>
                    <span class='file-name-span'>${data.fileName}</span> 
                    <span class='file-size-span'>${$this.getSize(data.size)}</span>
                    </div>
                    </div>
                    <div class='file-down-div'>
                    <span class='file-down' href='${url}' download='${data.fileName}' target='_blank'>下载</span>
                    </div>
                    </div>`
                } else if (data.type == '2') {
                    content = `<img src=${url} alt="图片" />`
                } else if (data.type == '3') {
                    content = `<audio src=${url} alt="音频" controls="controls" />`
                } else if (data.type == '4') {
                    content = `<video controls poster width="280" alt="视频">
                    <source src=${url} type="video/mp4">
                    </video>`
                } else if (data.type == '5') { //其他
                    content = `<div class='upload-div'>
                    <div class='uploadfile-div'><i class='uploadfile-icon'></i>
                    <div class='uploadfile-div-right'>
                    <span class='file-name-span'>${data.fileName}</span> 
                    <span class='file-size-span'>${$this.getSize(data.size)}</span>
                    </div>
                    </div>
                    <div class='file-down-div'>
                    <span class='file-down' href='${url}' download='${data.fileName}' target='_blank'>下载</span>
                    </div>
                    </div>`
                } else if (data.type == '6') {//压缩包
                    content = `<div class='upload-div'>
                    <div class='uploadfile-div'><i class='uploadfile-icon uploadfile-icon-zip'></i>
                    <div class='uploadfile-div-right'>
                    <span class='file-name-span'>${data.fileName}</span> 
                    <span class='file-size-span'>${$this.getSize(data.size)}</span>
                    </div>
                    </div>
                    <div class='file-down-div'>
                    <span class='file-down' href='${url}' download='${data.fileName}' target='_blank'>下载</span>
                    </div>
                    </div>`
                }
                setTimeout(() => {
                    $this.setState({
                        chatContent: content
                    }, () => {
                        $this.sendPrivateMessage('img');
                    })
                }, 1500);

                console.log('onSuccess', ret);
            },
            onError(err) {
                console.log('onError', err);
                let chatArr = $this.state.chatHistory.concat([]);
                let falseIndex = chatArr.findIndex(item => ((item.content.indexOf('<img') > -1 || item.content.indexOf('<audio') > -1
                    || item.content.indexOf('<video') > -1 || item.content.indexOf('uploadfile-div') > -1) && item.sending === 1));
                console.log('falseIndex', falseIndex);
                chatArr[falseIndex].sending = 0;
                setTimeout(() => {
                    $this.setState({
                        chatHistory: chatArr,
                    })
                }, 3000);
            },
            beforeUpload(file, fileList) {
                console.log(file, 'fileList', fileList);
                let chatArr = chatHistory.concat([]);
                if (file.size < 45 * 1024 * 1024) {
                    if (file.type.indexOf('audio/') > -1) {
                        const reader = new FileReader();
                        console.log('reader', reader);
                        reader.onloadend = () => {
                            let data = {
                                content: `<audio src=${reader.result} alt="音频" controls="controls" />`, // 替换为实际的消息内容
                                sessionId: session.sessionId,
                                createdTime: dayjs().format(),
                                schoolId: userInfo.schoolId,
                                senderId: userInfo.userId,
                                sending: 1,//1正在发送，2发送完成,0发送失败
                            }
                            chatArr.push(data);
                            $this.setState({
                                chatHistory: chatArr
                            }, () => {
                                $this.scrollToBottom();
                                return new Promise(resolve => {
                                    console.log('start check', chatArr);
                                    setTimeout(() => {
                                        console.log('check finshed');
                                        resolve(file);
                                    }, 1000);
                                });
                            })
                        };
                        reader.readAsDataURL(file);
                    } else if (file.type.indexOf('video/') > -1) {
                        const reader = new FileReader();
                        console.log('reader', reader);
                        reader.onloadend = () => {
                            let data = {
                                content: `<video controls poster width="280" alt="视频">
                                <source src=${reader.result} type="video/mp4">
                                </video>`, // 替换为实际的消息内容
                                sessionId: session.sessionId,
                                createdTime: dayjs().format(),
                                schoolId: userInfo.schoolId,
                                senderId: userInfo.userId,
                                sending: 1,//1正在发送，2发送完成,0发送失败
                            }
                            chatArr.push(data);
                            $this.setState({
                                chatHistory: chatArr
                            }, () => {
                                $this.scrollToBottom();
                                return new Promise(resolve => {
                                    console.log('start check');
                                    setTimeout(() => {
                                        console.log('check finshed');
                                        resolve(file);
                                    }, 1000);
                                });
                            })
                        };
                        reader.readAsDataURL(file);
                    } else if (file.type.indexOf('image/') > -1) {
                        const reader = new FileReader();
                        console.log('reader', reader);
                        reader.onloadend = () => {
                            let data = {
                                content: `<img src=${reader.result} alt="图片" />`, // 替换为实际的消息内容
                                sessionId: session.sessionId,
                                createdTime: dayjs().format(),
                                schoolId: userInfo.schoolId,
                                senderId: userInfo.userId,
                                sending: 1,//1正在发送，2发送完成,0发送失败
                            }
                            chatArr.push(data);
                            $this.setState({
                                chatHistory: chatArr
                            }, () => {
                                $this.scrollToBottom();
                                return new Promise(resolve => {
                                    console.log('start check');
                                    setTimeout(() => {
                                        console.log('check finshed');
                                        resolve(file);
                                    }, 1000);
                                });
                            })
                        };
                        reader.readAsDataURL(file);
                    } else {
                        console.log('file11', file);
                        // <span class='file-size-span'>${this.getSize(file.size)}</span>

                        let data = {
                            content: `<div class='upload-div'>
                            <div class='uploadfile-div'><i class='uploadfile-icon'></i>
                            <div class='uploadfile-div-right'>
                            <span class='file-name-span'>${file.name}</span> 
                            <span class='file-size-span'>${$this.getSize(file.size)}</span>
                            </div>
                            </div>
                            </div>
                            `,
                            sessionId: session.sessionId,
                            createdTime: dayjs().format(),
                            schoolId: userInfo.schoolId,
                            senderId: userInfo.userId,
                            sending: 1,//1正在发送，2发送完成,0发送失败
                        }
                        chatArr.push(data);
                        $this.setState({
                            chatHistory: chatArr
                        }, () => {
                            $this.scrollToBottom();
                            return new Promise(resolve => {
                                console.log('start check');
                                setTimeout(() => {
                                    console.log('check finshed');
                                    resolve(file);
                                }, 1000);
                            });
                        })
                    }
                } else {
                    message.warn('文件不能超过45MB！')
                    resolve();
                    return;
                }

            },
        };
        const uploadImgs = {
            action: window._chatBasicProxy + 'api/commons/file/batch/upload?modelName=chat-' + userInfo.userId + '&sysId=460',
            accept: 'image/*',
            multiple: false,
            name: 'files',
            headers: {
                Authorization: getQueryVariable('lg_tk') || sessionStorage.getItem('token'),
            },
            onStart(file) {
                console.log('onStart', file, file.name);
            },
            onSuccess(ret) {
                console.log('onSuccess', ret);
                let url = ret.data[0].url.replace(/ /g, "")
                $this.setState({
                    chatContent: `<img src=${url} alt="图片" />`
                }, () => {
                    $this.sendPrivateMessage('img');
                })
            },
            onError(err) {
                console.log('onError', err);
                let chatArr = $this.state.chatHistory.concat([]);
                let falseIndex = chatArr.findIndex(item => (item.content.indexOf('<img') > -1 && item.sending === 1));
                console.log('falseIndex', falseIndex);
                chatArr[falseIndex].sending = 0;
                setTimeout(() => {
                    $this.setState({
                        chatHistory: chatArr,
                    })
                }, 3000);
            },
            beforeUpload(file, fileList) {
                console.log(file, 'fileList', fileList);
                let chatArr = chatHistory.concat([]);
                if (file) {
                    const reader = new FileReader();
                    console.log('reader', reader);
                    reader.onloadend = () => {
                        let data = {
                            content: `<img src=${reader.result} alt="图片" />`, // 替换为实际的消息内容
                            sessionId: session.sessionId,
                            createdTime: dayjs().format(),
                            schoolId: userInfo.schoolId,
                            senderId: userInfo.userId,
                            sending: 1,//1正在发送，2发送完成,0发送失败
                        }
                        chatArr.push(data);
                        $this.setState({
                            chatHistory: chatArr
                        }, () => {
                            $this.scrollToBottom();
                            return new Promise(resolve => {
                                console.log('start check');
                                setTimeout(() => {
                                    console.log('check finshed');
                                    resolve(file);
                                }, 1000);
                            });
                        })
                    };
                    reader.readAsDataURL(file);
                }

            },
        };
        return (
            <LgBlockCard
                className={"g002-blockCard lg-skin-s2 " + (isIframe == '1' ? 'is-iframe' : '')}
                title=" "
            // supplement="我是补充信息"
            // component={<div className="g002-blockCard-component"> 其他组件 </div>}
            >
                {
                    isDownload ?
                        <div className='download-div'>
                            <LgLoadingDotRotation size="medium" text={downloadPercent + '%'}></LgLoadingDotRotation>
                        </div>
                        : ''
                }
                <div className="g002-blockCard-content" onClick={this.closeMoreMenu}>
                    {/* 左边 */}
                    {
                        isIframe == '1' ?//嵌入
                            '' :
                            <div className='content-left'>
                                <div className='content-left-search'>
                                    <LgSearch
                                        value={keyword}
                                        input={{
                                            placeholder: '输入关键字搜索...',
                                            onChange: (e) => this.setState({ keyword: e.target.value }),
                                            onKeyPress: (e) => {
                                                if (e.key === 'Enter') {
                                                    e.stopPropagation();
                                                    e.preventDefault();
                                                    this.setState({
                                                        isSearch: true,
                                                        pageNum: 1,
                                                    }, () => this.debounce(this.getSessionList, 500)
                                                    )
                                                }
                                            },
                                            autoComplete: 'off'
                                        }}
                                        onClear={() => this.setState({ keyword: '', isSearch: false, pageNum: 1, }, () => this.getSessionList())}
                                        onSearch={() => this.setState({ isSearch: true, pageNum: 1, }, () => this.getSessionList())}
                                    />
                                </div>
                                <div className='content-left-person'>
                                    <Scrollbars autoHide autoHideTimeout={100} >
                                        <ul className='content-left-ul'>
                                            {
                                                sessionList.length > 0 ? sessionList.map((item, index) => {
                                                    return (
                                                        <li className={'content-left-li ' + (item?.seat == 1 ? 'is-top' : '')} style={item?.sessionId == session?.sessionId ? { background: '#f1f4f8' } : {}} onClick={() => { this.chooseChatObj(item) }}>
                                                            {/* <li className='content-left-li' style={item.receiverId == session.receiverId ? { background: '#f1f4f8' } : {}} onClick={() => { this.chooseChatObj(item) }}> */}
                                                            <div className='content-li-left'>
                                                                <i style={{ backgroundImage: `url(${item?.receiverAvatarPath ? item?.receiverAvatarPath : ''})` }} className={'user-photo ' + (item?.groupId ? 'group-photo' : '')}></i>
                                                                <div className='user-name-left'>
                                                                    <div className='left-div'>
                                                                        <span className='user-name'>{item.receiverName || item.groupName}</span>
                                                                        {
                                                                            item?.block == 1 ?
                                                                                <i className='is-block'></i>
                                                                                : ''
                                                                        }
                                                                        {
                                                                            item?.block != 1 && item.remind == 0 ?
                                                                                <i className='is-nodisturb'></i>
                                                                                : ''
                                                                        }
                                                                    </div>
                                                                    {
                                                                        item?.lastMsg ? <span className='user-chat-history' >{this.getStr(item?.lastMsg)}</span> : ''
                                                                    }
                                                                </div>
                                                            </div>
                                                            <div className='content-li-right'>
                                                                <span style={{ color: '#999' }}>{this.formatTime(item.updated)}</span>
                                                                <i className='more-menu' onClick={(e) => this.openMoreMenu(e, item, index)}></i>
                                                            </div>
                                                            <div className='content-no-read'>{item?.unReadCount && item?.unReadCount != 0 ? item?.unReadCount : ''}</div>
                                                            {
                                                                menuVisible && menuIndex == index ?
                                                                    <ul className='left-ul-menu'>
                                                                        {/* 无法使用，暂时隐藏 */}
                                                                        <li onClick={(e) => this.manageSeat(e, item)}>{item.seat == '0' ? '置顶会话' : '取消置顶'}</li>
                                                                        <li onClick={(e) => this.delSession(e, item)}>移除会话</li>
                                                                        {
                                                                            item?.groupId ? '' :
                                                                                <li onClick={(e) => this.maskMessage(e, item, 'list')}>{item.block == '0' ? '屏蔽此人' : '取消屏蔽'}</li>
                                                                        }
                                                                        {
                                                                            item?.block == 1 ?
                                                                                '' :
                                                                                <li onClick={(e) => this.noDisturbMessage(e, item, 'list')}>{item.remind == '0' ? '开启消息通知' : '消息免打扰'}</li>
                                                                        }
                                                                        <li onClick={(e) => this.clearHistoryMsg(e, item, 'list')}>清空历史记录</li>
                                                                    </ul>
                                                                    : ''
                                                            }
                                                        </li>
                                                    )
                                                }) :
                                                    <div className='no-session'>
                                                        <LgEmpty>暂无会话</LgEmpty>
                                                    </div>
                                            }
                                        </ul>
                                    </Scrollbars>
                                </div>
                            </div>
                    }
                    {/* 右边 */}
                    {
                        (sessionList.length === 0 || notReceiver) && !isSearch ?
                            // sessionList.length === 0 ?
                            <div className='no-content'>
                                <i className="no-content-ibg"></i>
                                <span>早起的虫儿有鸟吃~</span>
                            </div>
                            :
                            <div className={'content-right ' + (!isSearch && sessionList.length < 2 ? 'content-right-less' : '')} style={{ borderLeft: isFull ? 'none' : '' }}>
                                {/* <div className='content-right-top'> */}
                                <div className='content-right-top' style={{ paddingRight: isIframe == 1 ? '48px' : '' }}>
                                    {
                                        isIframe == 1 ?
                                            <div className='close-iframe' onClick={this.closeIframe}>×</div>
                                            : ''
                                    }
                                    <div className='content-right-info'>
                                        <i style={{ backgroundImage: `url(${session?.receiverAvatarPath ? session?.receiverAvatarPath : ''})` }} className={'content-photo ' + (session?.groupId ? 'content-photo-group' : '')} onClick={() => { session?.groupId ? this.openSetting() : this.getUserInfo(session?.receiverId, 'user') }}></i>
                                        <div className={'content-text ' + (session?.groupId ? 'content-text-group' : '')}>
                                            <div>
                                                <span className='content-name'>{session && session?.receiverId ? <span>{session.receiverName}<span style={{ color: '#999' }}>({session.receiverId})</span></span> : session?.groupName}</span>
                                                {
                                                    session?.groupId ? '' :
                                                        <span className={`content-identity content-identity-${userType}`}>{userType == 6 ? '管理员' : userType == 8 ? '领导' : '其他'}</span>
                                                }
                                            </div>
                                            {
                                                session?.groupId ?
                                                    <div className='content-signature'>{groupUserList?.length}人</div>
                                                    :
                                                    <div className='content-signature' title={userObj?.sign ? userObj?.sign : ''}>{userObj?.sign ? userObj?.sign : '这个人很懒，什么也没有留下~'}</div>
                                            }
                                        </div>
                                    </div>
                                    {/* <i className='content-more' onClick={this.openSetting} ></i> */}
                                    <div className='content-more' onClick={this.openSetting} >. . .</div>
                                </div>
                                {
                                    isFull ?
                                        <><div className='is-full'></div>
                                            <div className='is-full-bottom'></div>
                                        </>
                                        : ''
                                }
                                <div className='content-right-middle' style={{ background: isFull ? 'rgba:(#000000,0.5)' : '' }}>
                                    <Scrollbars onScroll={this.handleScroll} autoHide autoHideTimeout={100} ref={this.scrollbarsRef} >
                                        {
                                            chatHistory && chatHistory.map((item, index) => {
                                                // console.log('item', item);
                                                // console.log(index, 'showIndex', showIndex);
                                                if (item.content == '***') {
                                                    return ''
                                                }
                                                return (
                                                    <>
                                                        {
                                                            (item?.isRecall == 1) || item?.msgState == 0 && item.senderId == userInfo.userId ?
                                                                // <div className='recall-message'>——  您撤回了一条消息{<span className='re-edit' onClick={() => this.recallMessage(item)}>,重新编辑 </span>} ——</div>
                                                                // <div className='recall-message'>——  您撤回了一条消息{item?.content.indexOf('<img') > -1 ? '' : <span className='re-edit' onClick={() => this.recallMessage(item)}>,重新编辑 </span>} ——</div>
                                                                <div className='recall-message'>——  {item?.content.indexOf('upload-div') > -1 ? '您撤回了一个文件' : '您撤回了一条消息'}{item?.content.indexOf('upload-div') > -1 ? '' : <span className='re-edit' onClick={() => this.recallMessage(item)}>&nbsp;重新编辑 </span>} ——</div>
                                                                :
                                                                item?.isBlock ?
                                                                    <div className='recall-message'>——  您已被对方屏蔽，无法发送消息 ——</div>
                                                                    :
                                                                    item?.msgState == 0 ?
                                                                        <div className='recall-message'>——  {item?.senderName ? item?.senderName : '对方'}撤回了一条消息  ——</div>
                                                                        :
                                                                        <div className={item?.senderId == userInfo.userId ? 'my-send' : 'other-send'} key={index}>
                                                                            {
                                                                                item?.isJustSend === 1 || item?.isOldSend === 1 ?
                                                                                    <div className='just-send'>{this.calculateTimeDifference(item?.createdTime)}</div>
                                                                                    : ''
                                                                            }
                                                                            <div style={{ display: 'flex' }}>
                                                                                {
                                                                                    session?.sessionType == 2 && item?.senderId != userInfo.userId ?
                                                                                        <div className='send-name'>
                                                                                            {item?.senderName}
                                                                                        </div>
                                                                                        : ''
                                                                                }
                                                                                <div className={'send-top ' + (session?.sessionType == 2 ? 'send-top-group' : '')} style={{ visibility: showTime && index == showTimeIndex ? 'visible' : 'hidden' }}>
                                                                                    {item?.createdTime ? dayjs(item?.createdTime).format('YYYY-MM-DD HH:mm:ss') : ''}
                                                                                </div>
                                                                                {
                                                                                    session?.sessionType == 2 && item?.senderId == userInfo.userId ?
                                                                                        <div className='send-name'>
                                                                                            {item?.senderName}
                                                                                        </div>
                                                                                        : ''
                                                                                }
                                                                            </div>
                                                                            {/* <div className='send-top' style={{ visibility: showTime && index == showTimeIndex ? 'visible' : 'hidden' }}>
                                                                                {item?.createdTime ? dayjs(item?.createdTime).format('YYYY-MM-DD HH:mm:ss') : ''}
                                                                            </div> */}
                                                                           <div className='send-middle'>
                                                                                {
                                                                                    item?.sending == 1 ? <i title='发送中' className='send-loading'></i> :
                                                                                        item?.sending == 0 ? <i title='发送失败' className='send-fail' onClick={() => this.alertAQuestion2(item)} ></i> :
                                                                                            <i className='recall-icon' style={{ visibility: isShowWithdraw && index == showIndex && (item?.senderId == userInfo.userId || groupInfo.groupUserRole == 0) ? 'visible' : 'hidden' }} onMouseLeave={() => { this.closeRevoke() }} onClick={() => { this.openRevoke1() }}>
                                                                                                <div className='recall-div' style={{ display: showWithdraw && index == showIndex ? '' : 'none' }} onMouseLeave={() => { this.closeRevoke1() }} onClick={() => { this.recallChat(item) }}><div className='recall-bg'>撤回</div></div></i>
                                                                                }
                                                                                <div className='send-content' onClick={this.openPreview} dangerouslySetInnerHTML={{ __html: decodeURIComponent(item?.content) }} onMouseOver={() => { this.openRevoke(item?.createdTime, index) }} onMouseLeave={() => this.setState({ showTime: false, showTimeIndex: 0 })}></div>
                                                                                <i className='my-photo' style={{ backgroundImage: `url(${(item?.senderId == userInfo.userId ? userInfo.photoPath : session?.receiverAvatarPath) || item?.avatarPath || item?.receiverAvatarPath})` }} onClick={() => this.getUserInfo(item?.senderId, 'user')}></i>
                                                                            </div>
                                                                            <div className='send-bottom'>  </div>
                                                                            {/* <div className='send-bottom'>已读</div> */}
                                                                        </div>
                                                        }
                                                    </>
                                                )
                                            })
                                        }
                                    </Scrollbars>
                                </div>
                                <div className='content-right-bottom'>
                                    <MyEditor id='editor' editorBan={groupInfo.groupUserRole == 0 ? false : allBanned} getHtmlContent={(html) => {
                                        this.setState({
                                            chatContent: html && html !== '<p><br></p>' ? html : ''
                                        })
                                    }} sendPrivateMessage={this.sendPrivateMessage} isClear={isClear} isReEdit={isReEdit} clear={clear} setClear={() => this.setState({ clear: false })}
                                        value={this.state.chatContent} setIsReEdit={() => this.setState({ isReEdit: false })} setFull={(boolean) => this.setState({ isFull: boolean })} isFull={isFull}
                                    />
                                    <div className='send-btn-div'>
                                        <span className='send-tip'>Enter发送，Ctrl+Enter换行</span>
                                        <LgButton className='send-btn' disable={groupInfo.groupUserRole == 0 ? false : allBanned} backgroundType='opacification' type='info' width={64} onClick={this.sendPrivateMessage} >发送</LgButton>
                                    </div>
                                    {
                                        isFull ? '' :
                                            allBanned && groupInfo.groupUserRole != 0 ?
                                                <>
                                                    <Tooltip color={"#333"} title='发送文件' arrowPointAtCenter={true} overlayStyle={{ color: 'red' }} placement="topRight">
                                                        <i className={'upload-icon upload-file ' + (allBanned ? 'no_send' : '')}></i>
                                                    </Tooltip>
                                                    <Tooltip color={"#333"} title='发送图片' arrowPointAtCenter={true} overlayStyle={{ color: 'red' }} placement="topRight">
                                                        <i className={'upload-icon upload-img ' + (allBanned ? 'no_send' : '')}></i>
                                                    </Tooltip>
                                                </>
                                                :
                                                <><LgUpload {...uploadFiles}>
                                                    <Tooltip color={"#333"} title='发送文件' arrowPointAtCenter={true} overlayStyle={{ color: 'red' }} placement="topRight">
                                                        <i className={'upload-icon upload-file '}></i>
                                                    </Tooltip>
                                                </LgUpload><LgUpload {...uploadImgs}>
                                                        <Tooltip color={"#333"} title='发送图片' arrowPointAtCenter={true} overlayStyle={{ color: 'red' }} placement="topRight">
                                                            <i className={'upload-icon upload-img '}></i>
                                                        </Tooltip>
                                                    </LgUpload></>
                                    }
                                </div>
                                {
                                    openSettingVisible ?
                                        <LgDrawer
                                            type={"right"}
                                            visible={openSettingVisible}
                                            oldButtonView={true}
                                            cover={true}
                                            width={380} title={'聊天设置'}
                                            closeBtn={() => { this.openSetting(); }}
                                            checkBtn={() => { this.openSetting(); }}
                                        >
                                            <div className='chat-setting'>
                                                {/* <div className='chat-setting-span'><span>聊天设置</span><i className='close-chat-setting' onClick={this.openSetting} ></i></div> */}
                                                {
                                                    session?.groupId ? '' :
                                                        <div className='block-person' >屏蔽此人<LgSwitch checked={blockPerson} onClick={() => this.blockAndDisturbing('block', blockPerson)} ></LgSwitch></div>
                                                }
                                                {
                                                    session?.block == 1 ?
                                                        <div className='no-disturbing'></div>
                                                        :
                                                        <div className='no-disturbing'>消息免打扰<LgSwitch checked={disturbing} onClick={() => this.blockAndDisturbing('disturbing', disturbing)}></LgSwitch></div>
                                                }
                                                <div className='view-chat-history' onClick={() => this.historyMessage()}><span style={{ marginLeft: '5px' }}>查看全部历史记录</span></div>
                                                {
                                                    session?.sessionType == 2 && groupInfo?.groupUserRole == 0 ?
                                                        <div className='view-chat-history' onClick={() => this.openBannedPop('bannedPop')}><span style={{ marginLeft: '5px' }}>设置群内禁言</span></div>
                                                        : ''
                                                }
                                                {
                                                    session?.groupId ?
                                                        <div className='session-user-list'>
                                                            <div className='session-user-span'>群组成员列表
                                                                <LgSearch
                                                                    value={groupUserKeyword}
                                                                    className='search-user'
                                                                    input={{
                                                                        placeholder: '输入关键字搜索...',
                                                                        onChange: (e) => this.setState({ groupUserKeyword: e.target.value }),
                                                                        onKeyPress: (e) => {
                                                                            if (e.key === 'Enter') {
                                                                                e.stopPropagation();
                                                                                e.preventDefault();
                                                                                this.setState({
                                                                                    userSearch: true
                                                                                }, () => this.searchGroupUser()
                                                                                )
                                                                            }
                                                                        },
                                                                        autoComplete: 'off',
                                                                    }}
                                                                    onClear={() => this.setState({ groupUserKeyword: '', userSearch: false })}
                                                                    onSearch={() => this.setState({ userSearch: true }, () => this.searchGroupUser())}
                                                                />
                                                            </div>
                                                            <Scrollbars autoHide autoHideTimeout={100}>
                                                                <div className='session-user-flex'>
                                                                    {
                                                                        userSearch ?
                                                                            searchGroupList.length > 0 ? searchGroupList.map(item => {
                                                                                return (
                                                                                    <div className='session-user-div' onClick={() => { this.setState({ groupUserItem: item }, () => { this.getUserInfo(item?.memberId, 'user') }) }}>
                                                                                        <i className='session-user-photo' style={{ backgroundImage: `url(${item.memberAvatarPath})` }}></i>
                                                                                        <div className='session-user-name'>{item.memberName}</div>
                                                                                        <div style={{marginTop: '-5px'}} className='session-user-userId'>{item.memberId}</div>
                                                                                    </div>
                                                                                )
                                                                            })
                                                                                :
                                                                                <div className='no-user'>
                                                                                    <LgEmpty size='large'>暂无相关用户</LgEmpty>
                                                                                </div>
                                                                            :
                                                                            groupUserList.map(item => {
                                                                                return (
                                                                                    <div className='session-user-div' onClick={() => { this.setState({ groupUserItem: item }, () => { this.getUserInfo(item?.memberId, 'user') }) }}>
                                                                                        <i className='session-user-photo' style={{ backgroundImage: `url(${item.memberAvatarPath})` }}></i>
                                                                                        <div className='session-user-name'>{item.memberName}</div>
                                                                                        <div style={{marginTop: '-5px'}} className='session-user-userId'>{item.memberId}</div>
                                                                                    </div>
                                                                                )
                                                                            })
                                                                    }
                                                                </div>
                                                            </Scrollbars>
                                                        </div>
                                                        : ''
                                                }
                                            </div>
                                        </LgDrawer>
                                        : ''
                                }
                                {
                                    openChatHistory ?
                                        <LgDrawer
                                            type={"right"}
                                            visible={openChatHistory}
                                            oldButtonView={true}
                                            cover={true}
                                            width={780}
                                            title={<>历史记录<LgButton type='info' shapeType='text' className="clear-history" onClick={() => this.clearHistoryMsg('', session, 'btn')}>清空</LgButton></>}
                                            closeBtn={() => { this.closeChat(); }}
                                            checkBtn={() => { this.closeChat(); }}
                                        >
                                            <div className='chat-history'>
                                                <div className='chat-history-middle'>
                                                    <div className='chat-history-left'>
                                                        <LgDatePicker className='date-picker lg-skin-s2' placeholder="请选择"
                                                            onChange={e => { this.selectDate(e) }} value={demonstrationValue}
                                                            disabledDate={time => time.getTime() > Date.now()} />
                                                        <LgCheckbox className='only-target' checked={onlyViewPerson} onChange={this.viewPerson} ></LgCheckbox> <span>只看{session?.groupId ? '其他人' : '对方'}的消息</span>
                                                    </div>
                                                    {
                                                        totalNum / pageHistorySize < 1 ?
                                                            '' :
                                                            <LgPaginationC total={Math.ceil(totalNum / pageHistorySize)} className='chat-pagination' size="small" currentPage={pageHistoryNum} onChangePage={this.changePage} />
                                                    }
                                                </div>
                                                <div className='chat-history-bottom'>
                                                    {
                                                        historyMessageList.length > 0 ?
                                                            <Scrollbars autoHide autoHideTimeout={100} right={'15px'} >
                                                                {
                                                                    historyMessageList.map((item, index) => {
                                                                        let prevSenderId = index > 0 ? historyMessageList[index - 1].senderId : null;
                                                                        let showBackgroundImage = item.senderId !== prevSenderId;
                                                                        return (
                                                                            <div key={item.messageId}>
                                                                                <div className='photo-name-time'>
                                                                                    <div className='photo-name-left'>
                                                                                        {
                                                                                            showBackgroundImage ?
                                                                                                <i className='chat-history-photo' style={{ backgroundImage: `url(${item.senderId == userInfo.userId ? (userInfo.photoPath) : ((userObj?.avatarPath == session.receiverAvatarPath ? userObj?.avatarPath : userObj?.photoPath))})` }}></i>
                                                                                                :
                                                                                                <i className='chat-history-photo'></i>
                                                                                        }
                                                                                        <span className='chat-history-name'>{item.senderId == userInfo.userId ? userInfo.userName : (session?.receiverName || item.senderId)}
                                                                                            {item.senderId == userInfo.userId && <span style={{ color: '#f60', }}>(我)</span>}
                                                                                        </span>
                                                                                    </div>
                                                                                    <span className='chat-history-time'>{dayjs(item.createdTime).format('YYYY-MM-DD HH:mm')}</span>
                                                                                </div>
                                                                                <div className='chat-message'>
                                                                                    <div className='chat-message-content' onClick={this.openPreview} dangerouslySetInnerHTML={{ __html: item?.content }} ></div>
                                                                                </div>
                                                                            </div>
                                                                        );
                                                                    })
                                                                }

                                                            </Scrollbars>
                                                            :
                                                            <div className='no-chat-history'>
                                                                <LgEmpty size='large'>当日没有消息记录</LgEmpty>
                                                            </div>
                                                    }
                                                </div>
                                            </div>
                                        </LgDrawer>
                                        : ''
                                }
                                {
                                    openBanned ?
                                        <LgDrawer
                                            type={"right"}
                                            visible={openBanned}
                                            oldButtonView={false}
                                            cover={true}
                                            width={400}
                                            title={'设置群内禁言'}
                                            closeBtn={() => { this.closeBanned('bannedPop'); }}
                                            checkBtn={() => { this.closeBanned('bannedPop'); }}
                                        >
                                            <div className='banned-manage'>
                                                <Scrollbars autoHide autoHideTimeout={100} autoHeight style={{ height: 'calc(100% - 10px)', minHeight: 'calc(100% - 10px)' }} autoHeightMin={'100%'}>
                                                    <div className='banned-top'>
                                                        <div style={{ marginBottom: '5px' }}>被禁言的成员</div>
                                                        <div className='banned-list'>
                                                            <div className='add-person' onClick={() => this.openBannedPop('bannedPer')}>
                                                                <i className='add-icon'></i>添加禁言成员
                                                            </div>
                                                            {
                                                                isBannedList.map((item, index) => {
                                                                    let photo = ''; // 初始化 photo 变量
                                                                    // 遍历 groupUserList，匹配 item.memberId
                                                                    for (let user of groupUserList) {
                                                                        if (user.memberId === item.memberId) {
                                                                            photo = user.memberAvatarPath; // 匹配成功，设置 photo 为对应的头像路径
                                                                            break; // 匹配成功后跳出循环
                                                                        }
                                                                    }
                                                                    return (
                                                                        <div className='banned_div'>
                                                                            <div className='banned_user'>
                                                                                <div className='banned_photo' style={{ backgroundImage: `url(${photo})` }}></div>
                                                                                <div>
                                                                                    <div className='banned_name'>{item.memberName + '(' + item.memberId + ')'}</div>
                                                                                    <div className='banned_time'>{this.getTimeDiff(Number(item.endTime))}</div>
                                                                                </div>
                                                                            </div>
                                                                            <div>
                                                                                <LgButton onClick={() => this.relieveBanned(item)}>解禁</LgButton>
                                                                            </div>
                                                                        </div>
                                                                    )
                                                                })
                                                            }
                                                        </div>
                                                    </div>
                                                    <div className='banned-bottom'>
                                                        <div className='banned-list'>
                                                            <div className='all-person-banned'>
                                                                <div>
                                                                    <div>全员禁言</div>
                                                                    <span className='banned-tip'>开启后，只允许群主和指定用户发言</span>
                                                                </div>
                                                                <div>
                                                                    <LgSwitch checked={allBanned} onClick={() => this.blockAndDisturbing('allBanned', allBanned)} ></LgSwitch>
                                                                </div>
                                                            </div>
                                                            {
                                                                allBanned ?
                                                                    <div>
                                                                        <div className='add-person' onClick={() => this.openBannedPop('bannedPerClose')}>
                                                                            <i className='add-icon'></i>添加可发言成员
                                                                        </div>
                                                                        {
                                                                            speakMemberList.map((item, index) => {
                                                                                let photo = ''; // 初始化 photo 变量
                                                                                // 遍历 groupUserList，匹配 item.memberId
                                                                                for (let user of groupUserList) {
                                                                                    if (user.memberId === item.memberId) {
                                                                                        photo = user.memberAvatarPath; // 匹配成功，设置 photo 为对应的头像路径
                                                                                        break; // 匹配成功后跳出循环
                                                                                    }
                                                                                }
                                                                                return (
                                                                                    <div className='banned_div'>
                                                                                        <div className='banned_user no_banned_user'>
                                                                                            <div className='banned_photo' style={{ backgroundImage: `url(${photo})` }}></div>
                                                                                            <div>
                                                                                                <div className='banned_name'>{item.memberName + '(' + item.memberId + ')'}</div>
                                                                                            </div>
                                                                                        </div>
                                                                                        <div>
                                                                                            <LgButton onClick={() => this.removeSpeak(item)}>移除</LgButton>
                                                                                        </div>
                                                                                    </div>
                                                                                )
                                                                            })
                                                                        }
                                                                    </div>
                                                                    : ''
                                                            }
                                                        </div>
                                                    </div>
                                                </Scrollbars>
                                            </div>
                                        </LgDrawer>
                                        : ''
                                }
                                {
                                    openBannedPerson ?
                                        <LgDrawer
                                            type={"right"}
                                            visible={openBannedPerson}
                                            oldButtonView={false}
                                            cover={true}
                                            width={700}
                                            title={'选择禁言成员'}
                                            closeBtn={() => { this.closeBanned('bannedPer'); }}
                                            checkBtn={() => { this.setBanned(); }}
                                            className='banned_select_drawer'
                                        >
                                            <div className='banned_select'>
                                                <div className='banned_left'>
                                                    <LgSearch
                                                        value={bannedKeyword}
                                                        className='search_banned'
                                                        input={{
                                                            placeholder: '输入关键字搜索...',
                                                            onChange: (e) => this.setState({ bannedKeyword: e.target.value }),
                                                            onKeyPress: (e) => {
                                                                if (e.key === 'Enter') {
                                                                    e.stopPropagation();
                                                                    e.preventDefault();
                                                                    if (bannedKeyword == '') return;
                                                                    this.setState({
                                                                        bannedSearch: true
                                                                    }, () => this.searchBannedUser()
                                                                    )
                                                                }
                                                            },
                                                            autoComplete: 'off',
                                                        }}
                                                        onClear={() => this.setState({ bannedKeyword: '', bannedSearch: false })}
                                                        onSearch={() => { if (bannedKeyword != '') { this.setState({ bannedSearch: true }, () => this.searchBannedUser()) } }}
                                                    />
                                                    {
                                                        bannedSearch ?
                                                            '' :
                                                            <div className='all_select' onClick={() => this.allSelect('banned')} >
                                                                <LgCheckbox checked={bannedAll} label={''} indeterminate={bannedSelectList.length > 0 && !bannedAll} />
                                                                <span style={{ marginLeft: '10px' }} >全选</span>
                                                            </div>
                                                    }
                                                    <Scrollbars autoHide autoHideTimeout={100} autoHeight style={{ height: 'calc(100% - 60px)', minHeight: 'calc(100% - 60px)' }} autoHeightMin={'100%'}>
                                                        {
                                                            bannedSearch ?
                                                                searchBannedList.length > 0 ? searchBannedList.map(item => {
                                                                    let isBanned = bannedSelectList.some(user => user.memberId === item.memberId);
                                                                    let notBanned = isBannedList.some(user => user.memberId === item.memberId);
                                                                    return (
                                                                        <div title={item.memberName + '(' + item.memberId + ')'} className='banned_left_div' onClick={() => { if (item.memberId != userInfo.userId && !notBanned) { this.selectBanned(item, 'banned') } }}>
                                                                            <LgCheckbox checked={isBanned} label={''} disabled={item.memberId == userInfo.userId || notBanned} />
                                                                            <i className='banned_left_photo' style={{ backgroundImage: `url(${item.memberAvatarPath})` }}></i>
                                                                            <div className='banned_left_name'>{item.memberName}</div>
                                                                            <div className='banned_left_userId'>（{item.memberId}）</div>
                                                                        </div>
                                                                    )
                                                                })
                                                                    :
                                                                    <div className='no_user_banned'>
                                                                        <LgEmpty size='large'>暂无相关用户</LgEmpty>
                                                                    </div>
                                                                :
                                                                bannedList.map(item => {
                                                                    let isBanned = bannedSelectList.some(user => user.memberId === item.memberId);
                                                                    let notBanned = isBannedList.some(user => user.memberId === item.memberId);
                                                                    return (
                                                                        <div title={item.memberName + '(' + item.memberId + ')'} className={'banned_left_div ' + (item.memberId == userInfo.userId || notBanned ? 'is_check' : '')} onClick={() => { if (item.memberId != userInfo.userId && !notBanned) { this.selectBanned(item, 'banned') } }}>
                                                                            <LgCheckbox checked={isBanned} label={''} disabled={item.memberId == userInfo.userId || notBanned} />
                                                                            <i className='banned_left_photo' style={{ backgroundImage: `url(${item.memberAvatarPath})` }}></i>
                                                                            <div className='banned_left_name'>{item.memberName}</div>
                                                                            <div className='banned_left_userId'>（{item.memberId}）</div>
                                                                        </div>
                                                                    )
                                                                })
                                                        }

                                                    </Scrollbars>
                                                </div>
                                                <div className='banned_right'>
                                                    <span style={{ color: '#333', marginLeft: '10px' }}>已选择（{bannedSelectList.length}/<span style={{ color: '#999' }}>200</span>）</span>
                                                    <span style={{ color: '#333', marginLeft: '10px' }}>禁言时间:</span>
                                                    <LgSelect className='time_select' datalist={timeList} size={'small'}
                                                        SelectOption={this.timeSelect}
                                                        value={selectValue} indexArr={[0]} >
                                                    </LgSelect>
                                                    <Scrollbars autoHide autoHideTimeout={100} autoHeight style={{ height: 'calc(100% - 30px)', minHeight: 'calc(100% - 30px)' }} autoHeightMin={'100%'}>
                                                        {
                                                            bannedSelectList.map(item => {
                                                                return (
                                                                    <div title={item.memberName + '(' + item.memberId + ')'} className={'banned_right_div'} >
                                                                        <div className='banned_right_back' onClick={() => { this.selectBanned(item, 'banned') }}>
                                                                            <i className='banned_right_photo' style={{ backgroundImage: `url(${item.memberAvatarPath})` }}></i>
                                                                            <div className='banned_right_name'>{item.memberName}</div>
                                                                            <div className='banned_right_userId'>（{item.memberId}）</div>
                                                                            <i className='banned_right_del'></i>
                                                                        </div>
                                                                    </div>
                                                                )
                                                            })
                                                        }
                                                    </Scrollbars>
                                                </div>
                                            </div>
                                        </LgDrawer>
                                        : ''
                                }
                                {
                                    cancelBannedPerson ?
                                        <LgDrawer
                                            type={"right"}
                                            visible={cancelBannedPerson}
                                            oldButtonView={false}
                                            cover={true}
                                            width={700}
                                            title={'选择可发言成员'}
                                            closeBtn={() => { this.closeBanned('bannedPerClose'); }}
                                            checkBtn={() => { this.setCanSpeak(); }}
                                            className='banned_select_drawer'
                                        >
                                            <div className='banned_select'>
                                                <div className='banned_left'>
                                                    <LgSearch
                                                        value={noBannedKeyword}
                                                        className='search_banned'
                                                        input={{
                                                            placeholder: '输入关键字搜索...',
                                                            onChange: (e) => this.setState({ noBannedKeyword: e.target.value }),
                                                            onKeyPress: (e) => {
                                                                if (e.key === 'Enter') {
                                                                    e.stopPropagation();
                                                                    e.preventDefault();
                                                                    if (noBannedKeyword == '') return;
                                                                    this.setState({
                                                                        noBannedSearch: true
                                                                    }, () => this.searchNoBannedUser()
                                                                    )
                                                                }
                                                            },
                                                            autoComplete: 'off',
                                                        }}
                                                        onClear={() => this.setState({ noBannedKeyword: '', noBannedSearch: false })}
                                                        onSearch={() => { if (noBannedKeyword != '') { this.setState({ noBannedSearch: true }, () => this.searchNoBannedUser()) } }}
                                                    />
                                                    {
                                                        noBannedSearch ?
                                                            '' :
                                                            <div className='all_select' onClick={() => this.allSelect('noBanned')}>
                                                                <LgCheckbox checked={noBannedAll} label={''} indeterminate={!noBannedAll && bannedSelectCloseList.length > 0} />
                                                                <span style={{ marginLeft: '10px' }}>全选</span>
                                                            </div>
                                                    }
                                                    <Scrollbars autoHide autoHideTimeout={100} autoHeight style={{ height: 'calc(100% - 60px)', minHeight: 'calc(100% - 60px)' }} autoHeightMin={'100%'}>
                                                        {
                                                            noBannedSearch ?
                                                                searchNoBannedList.length > 0 ? searchNoBannedList.map(item => {
                                                                    let isBanned = bannedSelectCloseList.some(user => user.memberId === item.memberId);
                                                                    let notBanned = speakMemberList.some(user => user.memberId === item.memberId);
                                                                    return (
                                                                        <div title={item.memberName + '(' + item.memberId + ')'} className='banned_left_div' onClick={() => { if (item.memberId != userInfo.userId && !notBanned) { this.selectBanned(item, 'noBanned') } }}>
                                                                            <LgCheckbox checked={isBanned} label={''} disabled={item.memberId == userInfo.userId || notBanned} />
                                                                            <i className='banned_left_photo' style={{ backgroundImage: `url(${item.memberAvatarPath})` }}></i>
                                                                            <div className='banned_left_name'>{item.memberName}</div>
                                                                            <div className='banned_left_userId'>（{item.memberId}）</div>
                                                                        </div>
                                                                    )
                                                                })
                                                                    :
                                                                    <div className='no_user_banned'>
                                                                        <LgEmpty size='large'>暂无相关用户</LgEmpty>
                                                                    </div>
                                                                :
                                                                noBannedList.map(item => {
                                                                    let isBanned = bannedSelectCloseList.some(user => user.memberId === item.memberId);
                                                                    let notBanned = speakMemberList.some(user => user.memberId === item.memberId);
                                                                    return (
                                                                        <div title={item.memberName + '(' + item.memberId + ')'} className={'banned_left_div ' + (item.memberId == userInfo.userId || notBanned ? 'is_check' : '')} onClick={() => { if (item.memberId != userInfo.userId && !notBanned) { this.selectBanned(item, 'noBanned') } }}>
                                                                            <LgCheckbox checked={isBanned} label={''} disabled={item.memberId == userInfo.userId || notBanned} />
                                                                            <i className='banned_left_photo' style={{ backgroundImage: `url(${item.memberAvatarPath})` }}></i>
                                                                            <div className='banned_left_name'>{item.memberName}</div>
                                                                            <div className='banned_left_userId'>（{item.memberId}）</div>
                                                                        </div>
                                                                    )
                                                                })
                                                        }

                                                    </Scrollbars>
                                                </div>
                                                <div className='banned_right'>
                                                    <span style={{ color: '#333', marginLeft: '10px' }}>已选择（{bannedSelectCloseList.length}/<span style={{ color: '#999' }}>200</span>）</span>
                                                    <Scrollbars autoHide autoHideTimeout={100} autoHeight style={{ height: 'calc(100% - 30px)', minHeight: 'calc(100% - 30px)' }} autoHeightMin={'100%'}>
                                                        {
                                                            bannedSelectCloseList.map(item => {
                                                                return (
                                                                    <div title={item.memberName + '(' + item.memberId + ')'} className={'banned_right_div'} >
                                                                        <div className='banned_right_back' onClick={() => { this.selectBanned(item, 'noBanned') }}>
                                                                            <i className='banned_right_photo' style={{ backgroundImage: `url(${item.memberAvatarPath})` }}></i>
                                                                            <div className='banned_right_name'>{item.memberName}</div>
                                                                            <div className='banned_right_userId'>（{item.memberId}）</div>
                                                                            <i className='banned_right_del'></i>
                                                                        </div>
                                                                    </div>
                                                                )
                                                            })
                                                        }
                                                    </Scrollbars>
                                                </div>
                                            </div>
                                        </LgDrawer>
                                        : ''
                                }
                                {
                                    openUserVisible ?
                                        // false ?
                                        <LgDrawer
                                            type={"right"}
                                            visible={openUserVisible}
                                            oldButtonView={true}
                                            cover={true}
                                            width={380} title={''}
                                            closeBtn={() => { this.openUserLgDrawer(); }}
                                            checkBtn={() => { this.openUserLgDrawer(); }}
                                            className='user-info-drawer'
                                        >
                                            <div className='user-info-top'>
                                                <div className='name-photo'>
                                                    <i className='show-photo' style={{
                                                        backgroundImage: `url(${(( openUserInfo?.avatarPath ==  session?.receiverAvatarPath || openUserInfo?.avatarPath == groupUserItem?.avatarPath) ? openUserInfo?.avatarPath :
                                                            openUserInfo?.userId == userInfo?.userId ? userInfo.photoPath : openUserInfo?.photoPath)})`
                                                        // backgroundImage: `url(${openUserInfo?.photoPath})`
                                                    }}></i>
                                                    <div className='show-name'>
                                                        <div className='show-name-top'>
                                                            <span className='user-name'>{openUserInfo?.receiverName || openUserInfo?.userName}</span>
                                                            <i className={'user-sex ' + (openUserInfo?.gender == '男' ? 'user-sex-man' : openUserInfo?.gender == '女' ? 'user-sex-woman' : '')}></i>
                                                        </div>
                                                        <div className='show-name-bottom'>
                                                            <span className='user-id'>{openUserInfo?.receiverId || openUserInfo?.userId}</span>
                                                            <i className='line'></i>
                                                            {/* <span>全体教师</span> */}
                                                            <span>{openUserInfo?.homeAddress}</span>
                                                        </div>
                                                    </div>
                                                </div>
                                                <div className='user-signature'>
                                                    <i className='user-signature-icon'></i>
                                                    <span className='user-signature-span' title={openUserInfo?.sign ? openUserInfo?.sign : ''}>{openUserInfo?.sign ? openUserInfo?.sign : '这个人很懒，什么也没有留下~'}</span>
                                                </div>
                                            </div>
                                            <div className='user-info-bottom'>
                                                <div className='user-phone'>
                                                    电话 <span>{openUserInfo?.telephone ? openUserInfo?.telephone : openUserInfo?.telephone2 ? openUserInfo?.telephone2 : '--'}</span>
                                                </div>
                                                <div className='user-qq'>
                                                    Q Q <span>{openUserInfo?.qq ? openUserInfo?.qq : '--'}</span>
                                                </div>
                                                <div className='user-vx'>
                                                    微信 <span>{openUserInfo?.weixin ? openUserInfo?.weixin : '--'}</span>
                                                </div>
                                                <div className='user-vb'>
                                                    微博 <span>{openUserInfo?.weibo ? openUserInfo?.weibo : '--'}</span>
                                                </div>
                                            </div>
                                        </LgDrawer>
                                        : ''
                                }
                            </div>
                    }
                </div>
            </LgBlockCard>
        );
    }
}
export default LineChat;